0

您好,我在解析 CSV 文件时遇到问题。CSV 文件用 | 分隔。特点 。到目前为止,一切都很好。但只有一个字段用 " 字符括起来。例如

field1|field2|"field3"|field4

当我设置

HasFieldsEnclosedInQuotes

为真,我将成为一个例外,否则 CSV 文件的解析会出错。你能帮我吗?

4

2 回答 2

0

我还没有看到一种文化,其中“|” 是 csv 分隔符...

总而言之,

var line = "field1|field2|\"field3\"|field4";
var pattern = string.Format("{0}(?=([^\"]*\"[^\"]*\")*[^\"]*$)", Regex.Escape("|")); 
//{0} in pattern is CSV separator. To get current use System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator
var splitted = Regex.Split(line, pattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture);

foreach (var s in splitted)
    Console.WriteLine(s);

输出:

field1
field2
"field3"
field4

模式旨在使用指定的分隔符从 CSV 文件中拆分单行。包括处理报价等。希望对您有所帮助。

于 2013-04-01T13:04:08.157 回答
-2

又快又脏:你可以考虑事先去掉所有使用"的文件。

string path = "c:\\test.txt";
string s = System.IO.File.ReadAllText(path, System.Text.Encoding.Default);
s = s.Replace("\"", string.Empty);
System.IO.File.WriteAllText(path, s, System.Text.Encoding.Default);

编辑 1:此方法适用于仅包含一个单词的数字列或字符串列,但在其他情况下可能会破坏您的 csv 结构(例如,字段存储 html 内容) - 请注意可能的副作用。

于 2013-04-01T12:48:00.140 回答