CSV带;分离到列,而最后有多个“”

时间:2017-01-06 12:21:19

标签: c# csv

我有一个程序可以生成一些数据的CSV文件。这些CSV文件由;"分隔,由于某种原因,它们以"结尾。现在这些是这些字符串的一些例子:

hello "; world "; 123 "
how "; are "; you "

现在这些行很容易阅读,但现在还有这样的行:

just "; a "; li"ne" "
and "; another "; one"1" "

由于这些行确实有",因此我的代码将失败并显示错误:Microsoft.VisualBasic.FileIO.MalformedLineException: Line x cannot be parsed using the current Delimiters.

我的代码现在看起来像这样:

using (TextFieldParser csvReader = new TextFieldParser(csv_file_path, Encoding.GetEncoding("windows-1250"))) //windows 1250 is the correct character encoding for European characters 
    {
        csvReader.SetDelimiters(new string[] { ";" });
        csvReader.HasFieldsEnclosedInQuotes = true;
                            while (!csvReader.EndOfData)
        {
            string[] fieldData = csvReader.ReadFields();
            for (int i = 0; i < fieldData.Length; i++)
            {
                if (fieldData[i] == "")
                {
                    fieldData[i] = null;
                }
            }
            csvData.Rows.Add(fieldData);
        }
    }

1 个答案:

答案 0 :(得分:1)

问题是你在我的评论中设置了错误的分隔符:

Linqpad

using (TextFieldParser csvReader = new TextFieldParser(@"C:\temp\temp.csv", Encoding.GetEncoding("windows-1252")))
{
    csvReader.SetDelimiters(new string[] { "\";" });
    csvReader.HasFieldsEnclosedInQuotes = false;
    while (!csvReader.EndOfData)
    {
        string[] fieldData = csvReader.ReadFields();
        for (int i = 0; i < fieldData.Length; i++)
        {
            if (fieldData[i] == "")
            {
                fieldData[i] = null;
            }
        }
        fieldData.Dump();
    }
}

输入数据

hello "; world "; 123 "
how "; are "; you "
just "; a "; li"ne" "
and "; another " one"1" "

输出

enter image description here