Home > Backend Development > C++ > How to Parse CSV Data with Commas Inside Fields Using C#?

How to Parse CSV Data with Commas Inside Fields Using C#?

Patricia Arquette
Release: 2025-01-26 16:51:10
Original
652 people have browsed it

How to Parse CSV Data with Commas Inside Fields Using C#?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template