C#processing CSV columns containing commas
When dividing the CSV file, you may encounter columns containing commas, such as embedded addresses or descriptions. Although the traditional boundary division method may fail in this case, there are some strong solutions in C#.
One method is to use the
class. Such a text files that are separated by the separation of the processing are allowed to perform specific processing of the fields of the quotation marks.
Microsoft.VisualBasic.FileIO.TextFieldParser
Consider the following CSV examples, the address column contains embedded commas:
To use to analyze this CSV, you can follow the following code example:
<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>
TextFieldParser
By setting to
<code class="language-csharp">using Microsoft.VisualBasic.FileIO; TextFieldParser parser = new TextFieldParser(new StringReader(csv)); parser.HasFieldsEnclosedInQuotes = true; parser.SetDelimiters(","); string[] fields; while (!parser.EndOfData) { fields = parser.ReadFields(); foreach (string field in fields) { Console.WriteLine(field); } } parser.Close();</code>
HasFieldsEnclosedInQuotes
The final output will correctly divide the CSV into each field, retain the embedded comma in the "Corvallis, or" address: true
TextFieldParser
The above is the detailed content of How to Handle CSV Columns Containing Embedded Commas in C#?. For more information, please follow other related articles on the PHP Chinese website!