c# - 如何拆分列可能包含逗号的csv

标签 c# .net csv

给定

2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,"Corvallis, OR",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34

如何使用C#将上述信息拆分成字符串如下:

2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis, OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

如您所见,其中一列包含 , <= (Corvallis, OR)

基于 C# Regex Split - commas outside quotes

string[] result = Regex.Split(samplestring, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

最佳答案

使用 Microsoft.VisualBasic.FileIO.TextFieldParser 类。这将处理分隔文件、TextReaderStream 的解析,其中一些字段用引号引起来,而另一些则没有。

例如:

using Microsoft.VisualBasic.FileIO;

string csv = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

TextFieldParser parser = new TextFieldParser(new StringReader(csv));

// You can also read from a file
// TextFieldParser parser = new TextFieldParser("mycsvfile.csv");

parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");

string[] fields;

while (!parser.EndOfData)
{
    fields = parser.ReadFields();
    foreach (string field in fields)
    {
        Console.WriteLine(field);
    }
} 

parser.Close();

这将导致以下输出:

2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis, OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

参见 Microsoft.VisualBasic.FileIO.TextFieldParser获取更多信息。

您需要在“添加引用 .NET”选项卡中添加对 Microsoft.VisualBasic 的引用。

关于c# - 如何拆分列可能包含逗号的csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6542996/

相关文章:

python - 使用时间模块时写入 csv 不起作用

c# - 在 EmguCV 中使用 cvKMeans2 出现异常

Java 与 C# 类名

c# - 我可以使用 'object' 关键字使方法更通用吗?

c# - 点击后退按钮时如何捕捉事件?

c# - .Net Core 2.1 - 无法访问已处置的对象。对象名称 : 'IServiceProvider'

c# - 我可以实现 DisposeBase 抽象类吗?

powershell - 在 Powershell 中修改现有 CSV 文件

c# - 从 C# 中的 Rust DLL 获取 UTF-8 编码的字符串

iphone - Json 或 CSV 到具有大量数据的 Web 服务