什么定界符可用于在其列中包含“,”的 .csv

What delimiter can be used for .csv that has "," in it's column

我想读取 .csv 文件并写入其他 .csv 文件。 我使用 streamwriter 并使用 string.splitdelimiter (',').

 using (StreamWriter file = new StreamWriter(destFile, true))
            {
                  string lines = System.IO.File.ReadAllLines(inputFile);
                  foreach (string line in lines)
                    {
                        if (line != lines[0])
                        {  
                            string[] values = line.Split(',');
                            file.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}",
                                    values[43], values[0], values[11], values[12], values[13], values[15], values[14], values[28], values[22], values[9]);
 }}}

但是,很少有列 , 在它的 data 中,如下所示,因此产生 incorrect output 因为程序将其计为 delimiter .

我试过使用 tinyCSVParser 库,但它也使用了会产生相同结果的定界符。当我更改为 CSVHelper 库时,它不使用定界符,但因为输入文件包含名称为 public double B/S 的列,所以我卡在那里,因为属性不能接受该名称。

[Name("B/S")]
private double p = 0;
public double B/S
{
    get
    {
        return p;
    }
    set
    {
        double result;
        result = double.Parse(Principal) * value / Day / 100;
        p = Math.Abs(result);
    }
}

我应该用什么替换 delimiter

推荐你用CSV-library写成csv-file。但是您可以在定义 RFC-4180.

中检查如何格式化 csv
  1. Each field may or may not be enclosed in double quotes (however some programs, such as Microsoft Excel, do not use double quotes at all). If fields are not enclosed with double quotes, then double quotes may not appear inside the fields.

如果我理解你的话...

试试这个:

using (StreamWriter file = new StreamWriter(destFile, true))     
{
    string lines = System.IO.File.ReadAllLines(inputFile);
    foreach (string line in lines)
    {
        string[] delimiter = line==lines[0] ? new string[]{","} : new string[]{"\",\"", "\""};
        string[] values = line.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
        //...
    }
}

编辑

看看这个:.NET Fiddle

注意:如果要用引号分割字符串,需要在字符串中使用反斜杠。参见:How to: Put Quotation Marks in a String (Windows Forms)