Reading a CSV file in .NET
One way to read a CSV file in C# is to use the Microsoft.VisualBasic.FileIO.TextFieldParser class. This class provides methods for parsing CSV files, including methods for setting the field delimiter and for reading fields from the file.
To use the TextFieldParser class, first create a new instance of the class and pass the file path to the constructor. Then, set the TextFieldType property to Delimited and set the Delimiters property to an array of strings that contains the delimiter characters used in the CSV file.
Next, use the ReadFields method to read the fields from the CSV file. The ReadFields method returns an array of strings, where each element in the array corresponds to a field in the CSV file.
The following code example shows how to use the TextFieldParser class to read a CSV file:
var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(file); parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited; parser.SetDelimiters(new string[] { ";" }); while (!parser.EndOfData) { string[] row = parser.ReadFields(); /* do something */ }
The above is the detailed content of How Can I Read a CSV File in .NET Using TextFieldParser?. For more information, please follow other related articles on the PHP Chinese website!