1

我想将 CSV 读取到数组,但 csv 在单元格内与换行符一致。

CSV ( csv 数据 )

标题、描述、标签、类别、私人、图像
MyGreatTitle1,"此行后为空行
空白行后的文本",techno,Tech,FALSE,C:\blogpostimg\img1.jpg
MyGreatTitle2,"此行后为空行
空白行后的文本",techno,Tech,FALSE,C:\blogpostimg\img2.jpg
MyGreatTitle3,"此行后为空行
空白行后的文本",techno,Tech,FALSE,C:\blogpostimg\img3.jpg
MyGreatTitle4,"此行后为空行
空白行后的文本",techno,Tech,FALSE,C:\blogpostimg\img4.jpg
MyGreatTitle5,"此行后为空行
空白行后的文本",techno,Tech,FALSE,C:\blogpostimg\img5.jpg
MyGreatTitle6,"此行后为空行
空白行后的文本",techno,Tech,FALSE,C:\blogpostimg\img6.jpg

我使用这段代码:

string dir = AppDomain.CurrentDomain.BaseDirectory + @"blogpost";
string[] allLines = File.ReadAllLines(dir + "csvdatabase.csv");

如何逐行读取csv但不在单元格内?

4

1 回答 1

2

正如 cirrus 所说,您可能应该使用专用的 CSV 库,但如果您想自己做(或了解如何做),这里有一个快速编写的 CSV 解析器,可以给您一个想法。它不处理完整的 CSV 标准,只处理您的特定要求!

public class CsvParser
{
    private readonly List<List<string>> entries = new List<List<string>>();
    private string currentEntry = "";
    private bool insideQuotation;

    /// <summary>
    ///   Returns all scanned entries.
    ///   Outer IEnumerable = rows,
    ///   inner IEnumerable = columns of the corresponding row.
    /// </summary>
    public IEnumerable<IEnumerable<string>> Entries
    {
        get { return entries; }
    }

    public void ScanNextLine(string line)
    {
        // At the beginning of the line
        if (!insideQuotation)
        {
            entries.Add(new List<string>());
        }

        // The characters of the line
        foreach (char c in line)
        {
            if (insideQuotation)
            {
                if (c == '"')
                {
                    insideQuotation = false;
                }
                else
                {
                    currentEntry += c;
                }
            }
            else if (c == ',')
            {
                entries[entries.Count - 1].Add(currentEntry);
                currentEntry = "";
            }
            else if (c == '"')
            {
                insideQuotation = true;
            }
            else
            {
                currentEntry += c;
            }
        }

        // At the end of the line
        if (!insideQuotation)
        {
            entries[entries.Count - 1].Add(currentEntry);
            currentEntry = "";
        }
        else
        {
            currentEntry += "\n";
        }
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        string dir = AppDomain.CurrentDomain.BaseDirectory + @"blogpost";
        string[] allLines = File.ReadAllLines(dir + "csvdatabase.csv");

        CsvParser parser = new CsvParser();
        foreach (string line in allLines )
        {
            parser.ScanNextLine(line);
        }
    }
}
于 2013-01-07T14:52:50.013 回答