使用c#读取csv文件,并且不要在双引号中使用逗号 [英] Read csv file when with c# and dont read commas in double quotes

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

问题描述

我使用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;
}

你可以从我的代码中知道我测试字符串行的长度确保它的五个长。我的问题是,如果有一个字段在csv内用逗号,然后计算多于5.我的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)和许多第三方 - a href =http://filehelpers.sourceforge.net/ =noreferrer> 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.

这篇关于使用c#读取csv文件,并且不要在双引号中使用逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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