Reading and writing a CSV file in c # using csvHelper Example
Below is an example to write and read a csv
file using csvHelper Library in c sharp. First you will have to include the
csvHelper lib in to your project by going in to NuGet packages in your project
and adding it. Once you don’t that you can examine the below program and
implement the program.
NB:- The below is just a snippet of code and
the objects are not declared properly. So please make necessary changes before
running the program.
For writing a file-
public void
WriteFile(Data data)
{
String
pathIp = “input_your_filePath”;
StreamWriter writeIp = new StreamWriter(pathIp);
CsvWriter cswIp = new CsvWriter(writeIp);
//
this below line is for inserting a header in your CSV file. I am just writing “Data-table”
cswIp.WriteField("Data-table");
cswIp.NextRecord();
for (int i
= 0; i < data_length_rows; i++)
{
for (int j
= 0; j < data_length_columns; j++)
{
var item = data[i][j].ToString();
//the
data you want to write
cswIp.WriteField(item);
}
cswIp.NextRecord();
}
Console.WriteLine("CSV writing input completed....");
writeIp.Close();
}
For
reading a CSV file-
public ReadFile(Data
data)
{
String
pathIp = “input_your_filePath”;
StreamReader readIp = new StreamReader(pathIp);
CsvReader csrIp = new CsvReader(readIp);
for (int i
= 0; i < data.rows ; i++)
{
//
ignoring the first row
csrIp.Read();
for (int j
= 0; j < data.rows; j++)
{
var record = csrIp.GetField(idx);
/*idx is the index field where you want to take the data. you will have to increment it according to your logic*/
data[i][ j] = record;
}
}
readIp.Close();
}
Comments
Post a Comment