Home >Backend Development >C++ >How Can I Parse a CSV File with Comma-Delimited Columns in C#?

How Can I Parse a CSV File with Comma-Delimited Columns in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-26 17:11:10875browse

How Can I Parse a CSV File with Comma-Delimited Columns in C#?

Efficiently Handling Commas in C# CSV Parsing

Parsing CSV files becomes complex when dealing with comma-delimited columns. This article demonstrates a robust solution using the Microsoft.VisualBasic.FileIO.TextFieldParser class in C#.

The TextFieldParser class offers a significant advantage by intelligently handling both quoted and unquoted fields. This ensures accurate data extraction even when commas appear within a column's value.

Let's illustrate this with a practical 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>

The code initializes a TextFieldParser with the CSV data. Crucially, HasFieldsEnclosedInQuotes is set to true to enable the parser to correctly interpret quoted fields. The delimiter is set to a comma.

The while loop iterates through each line, and ReadFields() splits the line into an array of fields. The code then prints each field to the console. The using statement ensures proper resource cleanup.

This method provides a reliable way to parse CSV data, accurately preserving column values that contain embedded commas within quotation marks.

The above is the detailed content of How Can I Parse a CSV File with Comma-Delimited Columns in 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