Reading CSV files using C#

后端 未结 12 2510
野的像风
野的像风 2020-11-21 22:49

I\'m writing a simple import application and need to read a CSV file, show result in a DataGrid and show corrupted lines of the CSV file in another grid. For ex

12条回答
  •  -上瘾入骨i
    2020-11-21 23:35

    Don't reinvent the wheel. Take advantage of what's already in .NET BCL.

    • add a reference to the Microsoft.VisualBasic (yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL)
    • use the Microsoft.VisualBasic.FileIO.TextFieldParser class to parse CSV file

    Here is the sample code:

    using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
    {
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        while (!parser.EndOfData) 
        {
            //Processing row
            string[] fields = parser.ReadFields();
            foreach (string field in fields) 
            {
                //TODO: Process field
            }
        }
    }
    

    It works great for me in my C# projects.

    Here are some more links/informations:

    • MSDN: Read From Comma-Delimited Text Files in Visual Basic
    • MSDN: TextFieldParser Class

提交回复
热议问题