parse csv file in csharp

To parse CSV files in C#, you can use the built-in TextFieldParser class from the Microsoft.VisualBasic.FileIO namespace. Here's an example of how to read a CSV file and print out its contents:

main.cs
using Microsoft.VisualBasic.FileIO; // add this namespace to your code file

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

// create a TextFieldParser object and set its properties
TextFieldParser parser = new TextFieldParser(filePath);
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");

// read the CSV file line by line
while (!parser.EndOfData) {
    // get the current line and split it into fields
    string[] fields = parser.ReadFields();

    // do something with the fields (e.g. print them to the console)
    foreach (string field in fields) {
        Console.Write($"{field}\t");
    }
    Console.WriteLine();
}

// close the TextFieldParser object
parser.Close();
724 chars
25 lines

In this example, we first define the path to our CSV file. Then we create a TextFieldParser object and set its properties to indicate that our CSV file is a delimited file with commas as the delimiter. We then read the file line by line using a while loop, and for each line we split it into fields using the ReadFields() method. Finally, we do something with the fields (in this case, we print them to the console), and close the TextFieldParser object when we're done.

related categories

gistlibby LogSnag