Reading / Writing CSV Files

This is done using the NETXPF.Library.CSVAdapter class. This implements the CSV specification as per RFC 4180. The best (lowest memory usage) approach is to stream a CSV file, reading one record at a time. This is done by calling CSVAdapter.ReadRecord repeatedly until it returns null.

Reading an Entire File into Memory

List<string[]> records = CSVAdapter.Read(File.OpenRead("MyFile.csv"));
//do something with records

Streaming a File Row by Row

using(StreamReader sr = new StreamReader("MyFile.csv"))
{
  while(true)
  {
    List<string> record = CSVAdapter.ReadRecord(sr);
    if(record == null) break;
    //do something with record
  }
}

Writing to a CSV File

using(StreamWriter sw = new StreamWriter("MyFile.csv"))
{
  foreach(string[] record in records) //assuming 'records' is already declared as List<string[]>
  {
    sw.WriteLine(CSVAdapter.ToCSV(record));
  }
}

Last edited Sep 16, 2011 at 2:48 PM by dacris, version 4

Comments

No comments yet.