How to read and write data from a CSV file in C#

By FoxLearn 7/4/2024 8:06:07 AM   332
To read and write data from a CSV file in C#, you can use the StreamReader and StreamWriter classes from the System.IO namespace.

How to read a CSV file in C#

To read a CSV file in C#, you can use the StreamReader class. The StreamReader class allows you to read text from a file.

// Specify the path to the CSV file
string filePath = @"C:\path\file.csv";
// Use a StreamReader to read the file
using (var reader = new StreamReader(filePath))
{
     // Read and display lines from the file until the end of the file is reached
     while (!reader.EndOfStream)
     {
          string line = reader.ReadLine();
          Console.WriteLine(line); // Or process the line as needed
     }
}

After reading each line, you typically split the line into fields based on the CSV format.

// Split the data line into an array of values
string[] fields = line.Split(',');
foreach (var value in fields)
{
    Console.Write(value + " ");
}

We use the StreamReader class to read the contents of a file named file.csv. The while loop reads each line of the file until the end is reached. Within this loop, the ReadLine() method fetches each line of text from the file and stores it in the variable line.

To parse the line into individual fields based on the CSV format, we use the Split() method. This method splits the line string into an array of strings wherever it encounters a comma.

How to write a CSV file in C#

To write a CSV file in C#, you can use the StreamWriter class. The StreamWriter class allows you to write text to a file.

// Specify the path to the CSV file
string filePath = @"C:\path\to\your\file.csv";

// Example data to write (could be from any source)
string[] dataToWrite = { "John,Doe,28", "Jane,Smith,32" };

// Use a StreamWriter to write to the file
using (var writer = new StreamWriter(filePath))
{
     foreach (var line in dataToWrite)
     {
          writer.WriteLine(line); // Write each line of data
     }
}

Through this example, you can effectively read data from a CSV file or write data to a CSV file in C#.