简体   繁体   中英

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

I want to read.csv file and write to other.csv file. I use streamwriter and use string.split with delimiter (',') .

 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]);
 }}}

But, there are few column that has , in it's data such as shown below, thus producing incorrect output because the program has count it as the delimiter .

在此处输入图像描述

I have tried using tinyCSVParser library but it also using delimiter which will produce same result. When I change to CSVHelper library, it does not use delimiter but because the input file has column with name public double B/S , thus I stuck there because the properties cannot accept that name.

[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);
    }
}

What should I replace the delimiter with?

I recommend you use a CSV-library to write csv-file. But you can check how to format csv in the definition RFC-4180 .

  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.

If i understand you well...

Try this:

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);
        //...
    }
}

EDIT

Check this out: .NET Fiddle

Note: if you want to split string by qoutation mark, you need to use backslash in a string. See: How to: Put Quotation Marks in a String (Windows Forms)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM