Dealing with fields containing unescaped double quotes with TextFieldParser

后端 未结 6 886
佛祖请我去吃肉
佛祖请我去吃肉 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:26

    I agree with Hans Passant's advice that it is not your responsibility to parse malformed data. However, in accord with the Robustness Principle, some one faced with this situation may attempt to handle specific types of malformed data. The code I wrote below works on the data set specified in the question. Basically it detects the parser error on the malformed line, determines if it is double-quote wrapped based on the first character, and then splits/strips all the wrapping double-quotes manually.

    using (TextFieldParser parser = new TextFieldParser(reader))
    {
        parser.Delimiters = new[] { "," };
    
        while (!parser.EndOfData)
        {
            string[] fields = null;
            try
            {
                fields = parser.ReadFields();
            }
            catch (MalformedLineException ex)
            {
                if (parser.ErrorLine.StartsWith("\""))
                {
                    var line = parser.ErrorLine.Substring(1, parser.ErrorLine.Length - 2);
                    fields = line.Split(new string[] { "\",\"" }, StringSplitOptions.None);
                }
                else
                {
                    throw;
                }
            }
            Console.WriteLine("This line was parsed as:\n{0},{1}", fields[0], fields[1]);
        }
    }
    

    I'm sure it is possible to concoct a pathological example where this fails (e.g. commas adjacent to double-quotes within a field value) but any such examples would probably be unparseable in the strictest sense, whereas the problem line given in the question is decipherable despite being malformed.

提交回复
热议问题