This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 2.0+

Reading CSV Data

CSV files are useful for transferring information between systems that cannot be connected by another method. Reading the data from CSV files, or strings containing CSV information, is made easy with standard .NET framework classes.

Ignoring CSV Comments

Some CSV files include comments that are human-readable but that should be ignored by a parser. Usually such comments will be indicated by special symbols or strings, known as tokens, at the start of the line. As an example, modify the test CSV file so that it contains the following information. This contains three comment lines, each indicated by two hash characters (##).

## Headers - don't change!

## Employee starts here
## End of file

Unless you tell the TextFieldParser about the special characters it will attempt to parse the comments as CSV rows. You can specify a number of tokens using the CommentTokens property. The tokens should be provided as a string array.

using (TextFieldParser tfp = new TextFieldParser(@"c:\temp\test.txt"))
    tfp.Delimiters = new string[] { "," };
    tfp.CommentTokens = new string[] { "##" };
    while (!tfp.EndOfData)
        string[] fields = tfp.ReadFields();

Running the above program for the new file gives the following results:

{Name}  {Age}   {Salary}
{Bob}   {25}    {40000}
{Jim}   {31}    {45000}
{Sam}   {18}    {30000}
{Sue}   {28}    {42000}

Parsing Preloaded Information

You can use a TextFieldParser to read CSV data from a file, a stream or a TextReader. If you have a string containing CSV information that you wish to parse, you can easily do so by first loading the string into a StringReader instance. This can be passed into a TextFieldParser constructor, as StringReader is a subclass of TextReader.

For example, the following GetCsv method loads some CSV data into a string and uses this string as the basis for a StringReader. The method returns the new object as a TextReader.

private static TextReader GetCsv()
    string data = "Col1,Col2,Col3\n1,2,3\nA,B,C\n.,\",\",\"\"\"\"";
    return new StringReader(data);

The TextFieldParser can now be initialised from the result of the GetCsv method.

using (TextFieldParser tfp = new TextFieldParser(GetCsv()))
4 December 2012