C# C# StreamWriter: Writing Data to CSV File

  • Thread starter Thread starter kiwijoey
  • Start date Start date
Click For Summary
To write data to a CSV file using the StreamWriter class in C#, the following steps are essential. First, prepare the data in a suitable format, such as a string with comma-separated values. For example, the data "Bob,1,2,3\nJim,4,5,6\nTom,7,8,9" can be used. Next, specify the file path where the CSV will be saved, such as "C:\test1.txt". Utilize the StreamWriter class to create a new instance, passing the file path, a boolean for appending data, and the encoding type. Use the WriteLine method to write each line of data to the file. After writing, ensure to flush the StreamWriter to save changes and close the file to release resources. This process effectively creates a CSV file with the desired data.
kiwijoey
Messages
2
Reaction score
0
Can someone please, using the following data, show me how to write this data to a CSV file using the StreamWriter class in C#.

Bob,1,2,3
Jim,4,5,6
Tom,7,8,9
 
Technology news on Phys.org
using System.IO; // file readers and writers

string myInputLine = "some line to be written to a file";

string fileSpecification = "C:\test1.txt";

StreamWriter filewriter = new StreamWriter(
fileSpecification, true, System.Text.Encoding.UTF8);

filewriter.WriteLine(myInputLine);
filewriter.Flush();

filewriter.Close();
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 19 ·
Replies
19
Views
943
  • · Replies 14 ·
Replies
14
Views
7K
  • · Replies 9 ·
Replies
9
Views
4K
Replies
19
Views
4K
  • · Replies 5 ·
Replies
5
Views
1K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
Replies
81
Views
7K
  • · Replies 2 ·
Replies
2
Views
3K