Skip to main content

How to Use CSV Classes

The CSV classes collection provides two classes – CsvReader, CsvWriter – which are used directly to read and write CSV files, a class with shared constants, CsvConstants, and a CsvParseException which may be thrown while reading a CSV stream (in addition to the usual System.IO exceptions).

The classes move tabular data between an internal representation of an array of string arrays (String[][]) and a Stream (e.g. FileStream).

The following features are supported:

  • Read CSV data from a Stream into an array of string arrays.
  • Write CSV data to a Stream from an array of string arrays.
  • Read or Write individual records to/from a string array.
  • Read or Write individual Fields to/from a string.

This page presents some basic examples of how the classes can be used. For more examples, refer to the Test classes and sample applications also in the GitHub repository.

Read CSV Data From a Stream

CSV data may be read from a Stream – the following snippet of code shows how to read from a file:

Write CSV Data To a Stream

Data may be written in CSV format to a Stream – the following snippet of code shows how to write data to a CSV file:

Read or Write A Record

To read or write a record of data, the following code may be used:

Read or Write Individual Fields

To read or write an individual field, the following code may be used:

Options

When writing fields, the class checks if each field contains data that needs to be quoted. This behaviour is modified using the QuoteLimit value – initially set to 1000. Any string less than or equal to QuoteLimit is checked – any over that number is simply quoted anyway. Set it to 0 to quote all except empty fields.

The separator used is by default (and by definition) a comma (‘,’), but this may be changed by setting the value of Separator to the desired character.

Finally, the quote character used is by default a double quote (‘”’), but this may be changed by setting the value of Quote to the desired character.

Both of the default characters (Quote and Separator) are defined in CsvConstants.