Parsing CSV files in C#, with header

后端 未结 17 1944
悲哀的现实
悲哀的现实 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 06:59

    Here is a helper class I use often, in case any one ever comes back to this thread (I wanted to share it).

    I use this for the simplicity of porting it into projects ready to use:

    public class CSVHelper : List
    {
      protected string csv = string.Empty;
      protected string separator = ",";
    
      public CSVHelper(string csv, string separator = "\",\"")
      {
        this.csv = csv;
        this.separator = separator;
    
        foreach (string line in Regex.Split(csv, System.Environment.NewLine).ToList().Where(s => !string.IsNullOrEmpty(s)))
        {
          string[] values = Regex.Split(line, separator);
    
          for (int i = 0; i < values.Length; i++)
          {
            //Trim values
            values[i] = values[i].Trim('\"');
          }
    
          this.Add(values);
        }
      }
    }
    

    And use it like:

    public List GetPeople(string csvContent)
    {
      List people = new List();
      CSVHelper csv = new CSVHelper(csvContent);
      foreach(string[] line in csv)
      {
        Person person = new Person();
        person.Name = line[0];
        person.TelephoneNo = line[1];
        people.Add(person);
      }
      return people;
    }
    

    [Updated csv helper: bug fixed where the last new line character created a new line]

提交回复
热议问题