Home >Backend Development >C++ >How to Parse CSV Files with Comma-Delimited Fields Enclosed in Quotes Using C#?

How to Parse CSV Files with Comma-Delimited Fields Enclosed in Quotes Using C#?

DDD
DDDOriginal
2025-01-26 17:06:10970browse

How to Parse CSV Files with Comma-Delimited Fields Enclosed in Quotes Using C#?

Handling Commas Within Quotes in CSV Parsing with C#

Correctly parsing CSV files becomes complex when fields contain commas themselves. This article demonstrates a robust C# solution for extracting data from such CSV files, focusing on scenarios where comma-delimited fields are enclosed in double quotes.

The challenge arises when a field, such as "Corvallis, OR," contains a comma within its quoted content. Standard string splitting based on commas would fail in this case. The solution lies in using the Microsoft.VisualBasic.FileIO.TextFieldParser class.

This class is specifically designed to handle delimited files with quoted fields. Here's a C# code example:

<code class="language-csharp">using Microsoft.VisualBasic.FileIO;
using System.IO;

string csvData = "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(csvData)))
{
    parser.HasFieldsEnclosedInQuotes = true;
    parser.SetDelimiters(",");

    while (!parser.EndOfData)
    {
        string[] fields = parser.ReadFields();
        foreach (string field in fields)
        {
            Console.WriteLine(field);
        }
    }
}</code>

This code snippet effectively parses the CSV data, correctly handling fields enclosed in quotes, ensuring that commas within those quotes are treated as part of the field and not as delimiters. The using statement ensures proper resource management by automatically closing the TextFieldParser. This approach guarantees accurate data extraction from CSV files even with complex field structures.

The above is the detailed content of How to Parse CSV Files with Comma-Delimited Fields Enclosed in Quotes Using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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