Parsing CSV files in C#, with header

后端 未结 17 1668
悲哀的现实
悲哀的现实 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:04

    This solution is using the official Microsoft.VisualBasic assembly to parse CSV.

    Advantages:

    • delimiter escaping
    • ignores Header
    • trim spaces
    • ignore comments

    Code:

        using Microsoft.VisualBasic.FileIO;
    
        public static List> ParseCSV (string csv)
        {
            List> result = new List>();
    
    
            // To use the TextFieldParser a reference to the Microsoft.VisualBasic assembly has to be added to the project. 
            using (TextFieldParser parser = new TextFieldParser(new StringReader(csv))) 
            {
                parser.CommentTokens = new string[] { "#" };
                parser.SetDelimiters(new string[] { ";" });
                parser.HasFieldsEnclosedInQuotes = true;
    
                // Skip over header line.
                //parser.ReadLine();
    
                while (!parser.EndOfData)
                {
                    var values = new List();
    
                    var readFields = parser.ReadFields();
                    if (readFields != null)
                        values.AddRange(readFields);
                    result.Add(values);
                }
            }
    
            return result;
        }
    

提交回复
热议问题