How to read and write CSV files in C#?
In C#, you can use the StreamReader and StreamWriter classes under the System.IO namespace to read and write CSV files.
Firstly, we need to create a CSV file and write data to it. We can use the StreamWriter class to open the file, write the data, and then close the file. Here is an example:
using System;
using System.IO;
class Program
{
static void Main()
{
// 创建CSV文件并写入数据
using (StreamWriter writer = new StreamWriter("data.csv"))
{
writer.WriteLine("Name, Age, City");
writer.WriteLine("John, 25, New York");
writer.WriteLine("Jane, 30, London");
}
Console.WriteLine("CSV文件写入成功!");
// 读取CSV文件
using (StreamReader reader = new StreamReader("data.csv"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] values = line.Split(',');
foreach (string value in values)
{
Console.Write(value.Trim() + " ");
}
Console.WriteLine();
}
}
}
}
In the code above, we first create a CSV file named “data.csv” using the StreamWriter class and write data to the file. Then, we open the CSV file using the StreamReader class and read data line by line using the ReadLine() method. Next, we use the Split() method to split each line of data into a string array and use the Trim() method to remove any leading or trailing spaces. Finally, we output the data to the console.
Please note that in practical use, proper error handling and exception handling for reading and writing CSV files is necessary for both file paths and data.