Not logged in - Login

Parse CSV

The following is an example of how to parse a CSV file that may contain a ',' character within a field.

You must add a 'Microsoft.VisualBasic' to the references in your project.

// the CSV import line to parse.
const string sImportLine = "2,1999,3/16/2017,\"Callison,James\",\"1234\",,\"He said, \"\"this is crazy!\"\"\",5' 10\" (178 centimeters)";

StringBuilder sbOutput = new StringBuilder(sImportLine);
// create a stream reader object out of the import line that needs to be parsed.
using (var stream = new System.IO.StringReader(sImportLine))
// create an instance of the parser object. (There are other constructors that take various parameters)
using (Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(stream))
   // set some properties on the parser object.
   parser.HasFieldsEnclosedInQuotes = true;
   parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;

   // declare a string array that will hold the parsed values.
   string[] fields;

   // keep going while there is still data to be read. (Note: this example will only have 1 line)
   while (!parser.EndOfData)
      // parse the fields and store them into our string array.
      fields = parser.ReadFields();

      // do something with the parsed fields.
      if (fields != null)
         // iterate through our string array
         foreach (var fld in fields)
            // add the field to a separate line in the StringBuilder object.

   // close the parser object.

See also Import a CSV file