Introduction
I have lost count of the number of projects I have worked on that required me to write data in a CSV format and present it to the user for download. On a recent project, I decided that it would be a good idea to implement some classes that would simplify the process of reading from and writing to a CSV file.
I had a scan around on the web to find a simple solution to the problem. There were many classes that already do this, but I found them way too complex.
So I decided to build my own!
Using the Code
Below are a few samples of how the classes can be used. The classes have many constructor and method overloads that allow reading/writing from/to files, strings and streams.
Using the CsvReader Class
List<List<string>> records = new List<List<string>>();
using (CsvReader reader = new CsvReader(FilePath, Encoding.Default))
{
while (reader.ReadNextRecord())
records.Add(reader.Fields);
}
The CsvReader class has the following properties:
TrimColumns - Gets or sets whether column and heading values should be trimmed
HasHeaderRow - Gets or sets whether the CSV content has a header row
Fields - Gets the fields in the current Record
FieldCount - Gets the number of fields in the current record
Using the CsvFile Class
CsvFile file = new CsvFile();
file.Populate(FilePath, true);
The CsvFile class has the following properties:
Headers - Gets the column headers
Records - Gets the records within the CSV file
HeaderCount - Gets the number of header columns
RecordsCount - Gets the number of records within the CSV file
Using the CsvWriter Class
CsvFile csvFile = new CsvFile();
csvFile.Populate(FilePath, true);
using (CsvWriter writer = new CsvWriter())
{
writer.WriteCsv(csvFile, FilePath);
}
The CsvWriter class has the following properties:
ReplaceCarriageReturnsAndLineFeedsFromFieldValues - Gets or sets whether carriage returns and line feeds should be replaced in field values.
CarriageReturnAndLineFeedReplacement - Gets or sets the character replacement for carriage returns and line feeds.
History
Version 1.0 (22-06-2010)