
When you call CsvFileWriter.WriteRow(), the row argument specifies the string values to write out. The CsvRow class derives from List, so it's basically just a list of strings. Using the codeīoth classes take a CsvRow argument. The writer class performs any encoding necessary, as I described above, and the reader class performs any necessary decoding.
#TEXTASTIC READ AND WRITE FILETYPE CODE#
This also simplifies the code because neither class needs to worry about which mode the file is in or protect against the user switching modes. NET stream classes generally seem to be split into reading and writing, I decided to follow that pattern with my CSV class and split it into CsvFileWriter and CsvFileReader. Listing 1: CsvFileWriter and CsvFileReader Classesīecause the. Return true if any columns read return (row.Count > 0) / /// /// public bool ReadRow(CsvRow row) / /// Reads a row of data from a CSV file / public class CsvFileReader : StreamReader / /// Class to read data from a CSV file Implement special handling for values that contain comma or quote // Enclose in quotes and double up any double quotes if ( value.IndexOfAny( new char \"", value.Replace( " \"", " \"\"")) Add separator if this isn't the first value if (!firstColumn) StringBuilder builder = new StringBuilder() / /// The row to be written public void WriteRow(CsvRow row) / /// Writes a single row to a CSV file. / public class CsvFileWriter : StreamWriter / /// Class to write data to a CSV file Listing 1 shows my CsvFileWriter and CsvFileReader classes. So this seems like a perfect task for a handy little C# class. In addition, two double quotes together signify a double quote in the value and not a value separator. The same is also done for values that contain double quotes. Double quotes are used to wrap values that contain commas so that the commas are not interpreted as a value separator. However, there is slightly more work involved. Each value is a field (or column in a spreadsheet), and each line is a record (or row in a spreadsheet). As the name suggestions, a CSV file is simply a plain text file that contains one or more values per line, separated by commas. CSV files can easily be read and written by many programs, including Microsoft Excel.įor the most part, reading and writing CSV files is trivial.

Comma-Separated Values (CSV) FilesĪ much simpler way to have your application share data is by reading and writing Comma-Separated Values (CSV) files. Although there are interfaces available to work with, for example, Microsoft Excel data files, this approach is generally complex, involves a fair amount of overhead, and requires that support libraries accompany your application. A common requirement is to have applications share data with other programs.
