Home > Backend Development > C++ > How to Properly Split CSV Columns with Embedded Commas in C#?

How to Properly Split CSV Columns with Embedded Commas in C#?

DDD
Release: 2025-01-26 16:56:10
Original
912 people have browsed it

How to Properly Split CSV Columns with Embedded Commas in C#?

Split CSV columns containing embedded commas in C#

CSV files usually use commas to separate columns. However, some columns may themselves contain commas, which can create challenges when splitting CSV data into different strings.

Question:

Given a CSV row:

<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

How can I split this line into an array of strings, ensuring that the "Corvallis, OR" text remains in one field?

Solution:

The provided regular expression only works on CSV data where all commas are outside or inside quotes. To solve this problem, consider using the Microsoft.VisualBasic.FileIO classes in the TextFieldParser namespace. This class is designed to handle delimited files where some fields are enclosed in quotes and others are not.

Code:

<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";

using (TextFieldParser parser = new TextFieldParser(new StringReader(csv)))
{
    parser.HasFieldsEnclosedInQuotes = true;
    parser.SetDelimiters(",");

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

Output:

<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

Note:

When using TextFieldParser, you need to add a reference to Microsoft.VisualBasic in the "Add Reference.NET" tab. The code also uses the using statement to ensure that the TextFieldParser is closed correctly.

The above is the detailed content of How to Properly Split CSV Columns with Embedded Commas in 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template