Split CSV columns containing embedded commas in C#
CSV files usually use commas to separate columns. However, some columns may themselves contain commas, which can create challenges when splitting CSV data into different strings.
Question:
Given a CSV row:
<code>2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,"Corvallis, OR",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34</code>
How can I split this line into an array of strings, ensuring that the "Corvallis, OR" text remains in one field?
Solution:
The provided regular expression only works on CSV data where all commas are outside or inside quotes. To solve this problem, consider using the Microsoft.VisualBasic.FileIO
classes in the TextFieldParser
namespace. This class is designed to handle delimited files where some fields are enclosed in quotes and others are not.
Code:
<code class="language-csharp">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"; using (TextFieldParser parser = new TextFieldParser(new StringReader(csv))) { parser.HasFieldsEnclosedInQuotes = true; parser.SetDelimiters(","); while (!parser.EndOfData) { string[] fields = parser.ReadFields(); foreach (string field in fields) { Console.WriteLine(field); } } }</code>
Output:
<code>2 1016 7/31/2008 14:22 Geoff Dalgas 6/5/2011 22:21 http://stackoverflow.com Corvallis, OR 7679 351 81 b437f461b3fd27387c5d8ab47a293d35 34</code>
Note:
When using TextFieldParser
, you need to add a reference to Microsoft.VisualBasic
in the "Add Reference.NET" tab. The code also uses the using
statement to ensure that the TextFieldParser
is closed correctly.
The above is the detailed content of How to Properly Split CSV Columns with Embedded Commas in C#?. For more information, please follow other related articles on the PHP Chinese website!