Dealing with fields containing unescaped double quotes with TextFieldParser

后端 未结 6 918
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-04 09:56

I am trying to import a CSV file using TextFieldParser. A particular CSV file is causing me problems due to its nonstandard formatting. The CSV in question has its fields

6条回答
  •  無奈伤痛
    2021-01-04 10:29

    Jordan's solution is quite good, but it makes an incorrect assumption that the error line will always begin with a double-quote. My error line was this:

    170,"CMS ALT",853,,,NON_MOVEX,COM,NULL,"2014-04-25",""  204 Route de Trays"
    

    Notice the last field had extra/unescaped double quotes, but the first field was fine. So Jordan's solution didn't work. Here is my modified solution based on Jordan's:

    using(TextFieldParser parser = new TextFieldParser(new StringReader(csv))) {
     parser.Delimiters = new [] {","};
    
     while (!parser.EndOfData) {
      string[] fields = null;
      try {
       fields = parser.ReadFields();
      } catch (MalformedLineException ex) {
       string errorLine = SafeTrim(parser.ErrorLine);
       fields = errorLine.Split(',');
      }
     }
    }
    

    You may want to handle the catch block differently, but the general concept works great for me.

提交回复
热议问题