Sunday, December 27, 2009

Parsing a csv file using C#

The process has been made very simple by referencing the Microsoft.VisualBasic.FileIO dll

Code can be written in a simplified version as :

string filename = "c:\testfile.csv";
TextFieldParser fldparser = null;

try
{

using (fldparser = new TextFieldParser(filename))
{
//When it is a delimited option between fields.
fldparser .TextFieldType = FieldType.Delimited;
//If it is a comma separated data.
fldparser.SetDelimiters(",");
//If the file has double quotes inclued in every column value.
fldparser.HasFieldsEnclosedInQuotes = true;


while (!fldparser.EndOfData)
{
string[] columnvalues = fldparser.ReadFields();
// If the csv file has 10 columns then declare the array as
// defined below.(change values accordingly).
string[] totalcolumns = new string[10];
int colcount = 0;
foreach (string val in parts)
{
totalcolumns[colcount] = val; colcount += 1;
}
}
}

}
catch (Exception ex)
{
}
finally
{

}

No comments:

Post a Comment