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\",http://www.somecompany.com,\"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.SetDelimiters(",");
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.
sbOutput.AppendLine();
sbOutput.Append(fld);
}
}
}
// close the parser object.
parser.Close();
}
Last modified by Mohit @ 4/7/2025 7:35:53 PM