Parsing CSV files in C#, with header

后端 未结 17 1969
悲哀的现实
悲哀的现实 2020-11-21 06:57

Is there a default/official/recommended way to parse CSV files in C#? I don\'t want to roll my own parser.

Also, I\'ve seen instances of people using ODBC/OLE DB to

17条回答
  •  深忆病人
    2020-11-21 07:25

    A CSV parser is now a part of .NET Framework.

    Add a reference to Microsoft.VisualBasic.dll (works fine in C#, don't mind the name)

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

    The docs are here - TextFieldParser Class

    P.S. If you need a CSV exporter, try CsvExport (discl: I'm one of the contributors)

提交回复
热议问题