Dealing with fields containing unescaped double quotes with TextFieldParser

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

    Working Solution :

    using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
                {
                    csvReader.SetDelimiters(new string[] { "," });
                    csvReader.HasFieldsEnclosedInQuotes = false;
                    string[] colFields = csvReader.ReadFields();
    
                    while (!csvReader.EndOfData)
                    {
                        string[] fieldData = csvReader.ReadFields();
                        for (i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                            else
                            {
                                if (fieldData[i][0] == '"' && fieldData[i][fieldData[i].Length - 1] == '"')
                                {
                                    fieldData[i] = fieldData[i].Substring(1, fieldData[i].Length - 2);
                                }
                            }
                        }
                        csvData.Rows.Add(fieldData);
                       }
                }
    

提交回复
热议问题