Home > Backend Development > C++ > How to Handle CSV Columns Containing Embedded Commas in C#?

How to Handle CSV Columns Containing Embedded Commas in C#?

Linda Hamilton
Release: 2025-01-26 17:01:11
Original
558 people have browsed it

How to Handle CSV Columns Containing Embedded Commas in C#?

C#processing CSV columns containing commas

When dividing the CSV file, you may encounter columns containing commas, such as embedded addresses or descriptions. Although the traditional boundary division method may fail in this case, there are some strong solutions in C#.

One method is to use the

class. Such a text files that are separated by the separation of the processing are allowed to perform specific processing of the fields of the quotation marks.

Microsoft.VisualBasic.FileIO.TextFieldParser Consider the following CSV examples, the address column contains embedded commas:

To use to analyze this CSV, you can follow the following code example:
<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

TextFieldParser By setting to

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

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
will process fields with quotation marks in different ways to prevent the comma from being regarded as a fixed boundary.

HasFieldsEnclosedInQuotes The final output will correctly divide the CSV into each field, retain the embedded comma in the "Corvallis, or" address: true TextFieldParser

By using the class, you can effectively handle the CSV column containing the embedded comma to ensure accurate data interpretation and operation.

The above is the detailed content of How to Handle CSV Columns Containing 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template