当阅读csv文件用C#和不读双引号逗号 [英] Read csv file when with c# and dont read commas in double quotes

查看:128
本文介绍了当阅读csv文件用C#和不读双引号逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用阅读使用C#在这里CSV文件是一个小的代码片断。

I'm reading a csv file using c# here is a little code snippet.

using (StreamReader readFile = new StreamReader("C:\\temp\\" + whichTable))
{
    while ((line = readFile.ReadLine()) != null)
    {
        row = line.Split(',');

        switch (row.Length)
        {
            case 5:
                if (counter == 0) 
                { 
                    break; 
                } 
                else
                {
                    v00.Add(Convert.ToInt32(Regex.Replace(row[0], @"[^\w\.@-]", "")));
                }

                if (row[1] == "") 
                { 
                    v01.Add((1)); 
                }
                else
                {
                    v01.Add(Convert.ToInt32(Regex.Replace(row[1], @"[^\w\.@-]", "")));
                }

                if(row[2]=="")
                {
                    v02.Add(2);
                } 
                else
                {
                    v02.Add(Convert.ToInt32(Regex.Replace(row[2], @"[^\w\.@-]", "")));
                }

                v3.Add(row[4]);
                v4.Add(row[3]);
                counter++;
                break;
        }
        counter++;
    }
    break;
}



你可以从我的代码告诉我测试的串排的长度确保其五个长完全一样。我的问题是,如果有一个逗号它,然后计算出更多的则5.我的CSV的CSV中的一个字段的格式正确,所以,当出现这种情况我确实有这方面的双引号。我怎样才能知道C#只算双引号外的逗号? 。那真是我的问题。

as you can tell from my code i test the length of the string row to make sure that its five long exactly. My problem is that if have a field within the csv with a comma it then calculates to more then 5. My csv is well formed so when that happens i do have a that field double quoted. How can i tell c# only count the commas outside of double quotes? Thats really my question.

推荐答案

不要自己解析CSV - 格式更难以正确地解析比大多数人意识到。有迹象表明,你可以改用许多exsisting良好的CSV分析器。

Don't parse CSV yourself - the format is more difficult to parse properly than most people realize. There are many exsisting good CSV parsers that you can use instead.

有是的 TextFieldParser 是住在的Microsoft.VisualBasic.FileIO 命名空间(常规.NET libarary)和许多第三方的 - 的FileHelpers 是一个流行的自由选择。

There is the TextFieldParser library that lives in the Microsoft.VisualBasic.FileIO namespace (regular .NET libarary), and many third party ones - FileHelpers is a popular free choice.

这篇关于当阅读csv文件用C#和不读双引号逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆