C# efficiently parses CSV data containing commas
During the parsing process of CSV files, commas are often encountered inside fields, which can lead to parsing errors. To handle this situation efficiently, you can use the Microsoft.VisualBasic.FileIO.TextFieldParser class.
The following code snippet demonstrates how to use the TextFieldParser class to parse a CSV string. Even if the field contains commas, it can be parsed correctly as long as it is enclosed in double quotes. The code reads the data, splits it into individual fields, and prints it to the console.
<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"; 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>
The analysis results are as follows:
<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>
By using the TextFieldParser class, you can effectively parse CSV data, correctly handle commas in fields, and ensure the accuracy of data processing and analysis.
The above is the detailed content of How to Parse CSV Data with Commas Inside Fields Using C#?. For more information, please follow other related articles on the PHP Chinese website!