CsvHelper删除引号

时间:2019-02-19 11:23:19

标签: c# .net csv csvhelper

我有很大的.csv文件,我想将它们完全列在.csv文件中的位置

示例.csv文件行应为

1141825007047,2019-02-18,02:55,"US","ATL","LAX","0","IAD","ORD","UA","UA236,UA208","UA2291,UA1155",2019-03-24 14:25,2019-03-24 22:20,2019-04-14 22:45,2019-04-15 08:54

当我使用CsvHelper并设置以下参数时:

csv.Configuration.BadDataFound = null;
csv.Configuration.IgnoreQuotes = true;
csv.Configuration.Delimiter = ",";

然后将“ UA236,UA208”之类的值分为两列,在我的情况下是不正确的。

如果我将参数设置为:

 csv.Configuration.BadDataFound = null;
 csv.Configuration.IgnoreQuotes = false;
 csv.Configuration.Delimiter = ",";

然后,列的格式确实正确,但是会删除所有引号。 关于引号,这是动态的事情,有些专栏会用到,有些则不会。

所需的输出应为字符串列表:

1141825007047
2019-02-18
02:55
"US"
"ATL"
"LAX"
"0"
"IAD"
"ORD"
"UA"
"UA236,UA208"
"UA2291,UA1155"
2019-03-24 14:25
2019-03-24 22:20
2019-04-14 22:45
2019-04-15 08:54

根据要求,添加一些代码:

 using (StreamReader reader = new StreamReader(myStream))
                {
                    using (CsvReader csv = new CsvReader(reader))
                    {
                        csv.Configuration.BadDataFound = null;
                        csv.Configuration.IgnoreQuotes = false;
                        csv.Configuration.Delimiter = ",";

                        while (csv.Read())
                        {
                            List<string> values = new List<string>();
                            string line = string.Empty;

                            for (int i = 0; csv.TryGetField<string>(i, out string value); i++)
                            {
                                values.Add(value);
                            }
                        }
                    }
                }

1 个答案:

答案 0 :(得分:0)

通过将Delimiter设置为,,将\n更改为IgnoreQuotes之类的true以外的任何字符,可以获得所需的输出

csv.Configuration.IgnoreQuotes = true;
csv.Configuration.Delimiter = "\\n";