如果包含双标记,则不要拆分字符串

Don't split the string if contains in double marks

我有一个文本分隔文件需要转换成数据table。给出这样的文本:

Name,Contact,Email,Date Of Birth,Address
JOHN,01212121,hehe@yahoo.com,1/12/1987,"mawar rd, shah alam, selangor"
JACKSON,01223323,haha@yahoo.com,1/4/1967,"neelofa rd, sepang, selangor"
DAVID,0151212,hoho@yahoo.com,3/5/1956,"nora danish rd, klang, selangor"

这就是我在 C# 中读取文本文件的方式

DataTable table = new DataTable();                

                    using (StreamReader sr = new StreamReader(path))
                    {
                        #region Text to csv
                        while (!sr.EndOfStream)
                        {
                            string[] line = sr.ReadLine().Split(',');
                            //table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]);

                            if (IsRowHeader)//Is user want to read first row as the header
                            {
                                foreach (string column in line)
                                {
                                    table.Columns.Add(column);
                                }

                                totalColumn = line.Count();

                                IsRowHeader = false;
                            }
                            else
                            {
                                if (totalColumn == 0)
                                {
                                    totalColumn = line.Count();

                                    for (int j = 0; j < totalColumn; j++)
                                    {
                                        table.Columns.Add();
                                    }

                                }

                                // create a DataRow using .NewRow()
                                DataRow row = table.NewRow();

                                // iterate over all columns to fill the row
                                for (int i = 0; i < line.Count(); i++)
                                {
                                    row[i] = line[i];
                                }

                                // add the current row to the DataTable
                                table.Rows.Add(row);
                            }          
                        }

列是动态的,用户可以在文本文件上添加或删除列。所以我需要检查有多少列并设置为数据table,之后我将读取每一行,将值设置为数据行然后将行添加到table.

如果不去掉双标里面的分号,会报错"Cannot find column 5",因为第一行只有4列(从0开始)。

处理文本分隔的最佳方法是什么?

不要尝试重新发明 CSV 解析轮。使用 .NET 内置的解析器:Microsoft.VisualBasic.FileIO.TextFieldParser

见。

我通常会选择这样的东西:

const char separator = ',';
using (var reader = new StreamReader("C:\sample.txt"))
{

    var fields = (reader.ReadLine() ?? "").Split(separator);

    // Dynamically add the columns
    var table  = new DataTable();
    table.Columns.AddRange(fields.Select(field => new DataColumn(field)).ToArray());

    while (reader.Peek() >= 0)
    {
        var line = reader.ReadLine() ?? "";

        // Split the values considering the quoted field values
        var values = Regex.Split(line, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)")
            .Select((value, current) => value.Trim())
            .ToArray()
            ;

        // Add those values directly
        table.Rows.Add(values);
    }

    // Demonstrate the results
    foreach (DataRow row in table.Rows)
    {
        Console.WriteLine();
        foreach (DataColumn col in table.Columns)
        {
            Console.WriteLine("{0}={1}", col.ColumnName, row[col]);
        }
    }
}

不,只是不要。不要尝试编写自己的 CSV 解析器 - 没有理由这样做。

This article explains the problem and recommends using FileHelpers - 够体面了。

还有一个Lumenworks reader,它更简单,也同样有用。

最后显然您可以使用数据集 link 到您的 CSV as described here。我没试过这个,但看起来很有趣,如果可能已经过时了。