Read and Write CSV in C#
In this article I'm going to explain how to read and write data from Csv file with row by row. Recently I'm in a situation to read inputs from Csv file and write data into Csv with row wise. I'm little bit confused about the approach either we have to go with Csv or excel, I implemented in both the ways but coming to performance as compare to Excel, Csv give better performance. In this article I will show you how to handle Csv file using C#.
Read and Write CSV:
Index:
1. Description
2. Read Csv File
2.1. ReadHeaders
3. Write Csv File
3.1. WriteCsvHeader
3.2. FormatCsv
4. Source Code
5. Output
6. Conclusion1. Description:
In this article I'm going to explain how to read and write data from csv file with row by row. Recently I'm in a situation to read inputs from csv file and write data into csv with row wise. I'm little bit confused about the approach either we have to go with csv or excel, I implemented in both the ways but coming to performance as compare to Excel, Csv give better performance. In this article I will show you how to handle Csv file using C#. To achieve this you have to include the dll of Lumenworks.Framework.IO dll as a reference to the project.
Get dll of Lumenworks.Framework.IO2. Read Csv File:
I just pass the path of the file as input and return the data in table format and store the same in DataTable.
public DataTable ReadCSV(string inputPath)
{
try
{
using (CsvReader csv = new CsvReader(new StreamReader(inputPath), true))
{
dtCSV = ReadHeaders(csv);
while (csv.ReadNextRecord())
{
DataRow drcsv = dtCSV.NewRow();
for (int i = 0; i < dtCSV.Columns.Count; i++)
{
drcsv[i] = dtCSV.Columns[i].ToString();
}
dtCSV.Rows.Add(drcsv);
dtCSV.AcceptChanges();
}
}
}
catch (Exception ex)
{
throw;
}
return dtCSV;
}2.1. ReadHeaders:
This method help us to read the headers of the Csv file in to temporary table, return type of this method is DataTable.
private DataTable ReadHeaders(CsvReader csv)
{
DataTable dt = new DataTable();
try
{
string[] strHeaders = csv.GetFieldHeaders();
foreach (string strCol in strHeaders)
{
dt.Columns.Add(strCol);
}
}
catch (Exception ex)
{
throw;
}
return dt;
}3. Write Csv File:
This mehod help us to write data into Csv file with comma separator, while writing into Csv file there are several issue we faced while the format of the Csv, so we used to convert it into appropriate format like "'" replace with "''".
public void WriteCSV(DataRow drMeta, string outputFilePath)
{
try
{
StringBuilder sb = new StringBuilder();
int cnt = File.ReadAllLines(outputFilePath).Length;
#region write csv headers
if (cnt == 0)
{
WriteCSVHeader(drMeta, outputFilePath);
}
#endregion
#region write csv rows
foreach (DataColumn dcMeta in drMeta.Table.Columns)
{
sb.Append(FormatCSV(drMeta[dcMeta.ColumnName].ToString()) + ",");
}
#endregion
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
File.AppendAllText(outputFilePath, sb.ToString());
}
catch (Exception ex)
{
throw;
}
}3.1. WriteCSVHeader:
This method help us to write the Headers into Csv file.
private void WriteCSVHeader(DataRow drMeta, string outputFilePath)
{
try
{
StringBuilder sb = new StringBuilder();
foreach (DataColumn dcMeta in drMeta.Table.Columns)
{
sb.Append(FormatCSV(dcMeta.ColumnName.ToString()) + ",");
}
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
File.AppendAllText(outputFilePath, sb.ToString());
}
catch (Exception ex)
{
throw;
}
}3.2. FormatCSV:
This method help us to Format Csv with appropriate format, in my case it's needed to format "'", to replace it with "''". The input of this method is input of the string.
private static string FormatCSV(string input)
{
try
{
input = input.Replace("\"", "\"\"");
return "\"" + input + "\"";
}
catch
{
throw;
}
}4. Source Code:
Source code of the project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using LumenWorks.Framework.IO.Csv;
namespace CSVReadWrite
{
public class CSVReadWrite
{
#region properties declaration
DataTable dtCSV = null;
#endregion
#region private methods
private DataTable ReadHeaders(CsvReader csv)
{
DataTable dt = new DataTable();
try
{
string[] strHeaders = csv.GetFieldHeaders();
foreach (string strCol in strHeaders)
{
dt.Columns.Add(strCol);
}
}
catch (Exception ex)
{
throw;
}
return dt;
}
private void WriteCSVHeader(DataRow drMeta, string outputFilePath)
{
try
{
StringBuilder sb = new StringBuilder();
foreach (DataColumn dcMeta in drMeta.Table.Columns)
{
sb.Append(FormatCSV(dcMeta.ColumnName.ToString()) + ",");
}
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
File.AppendAllText(outputFilePath, sb.ToString());
}
catch (Exception ex)
{
throw;
}
}
private static string FormatCSV(string input)
{
try
{
input = input.Replace("\"", "\"\"");
return "\"" + input + "\"";
}
catch
{
throw;
}
}
#endregion
#region public methods
public DataTable ReadCSV(string inputPath)
{
try
{
using (CsvReader csv = new CsvReader(new StreamReader(inputPath), true))
{
dtCSV = ReadHeaders(csv);
while (csv.ReadNextRecord())
{
DataRow drcsv = dtCSV.NewRow();
for (int i = 0; i < dtCSV.Columns.Count; i++)
{
drcsv[i] = dtCSV.Columns[i].ToString();
}
dtCSV.Rows.Add(drcsv);
dtCSV.AcceptChanges();
}
}
}
catch (Exception ex)
{
throw;
}
return dtCSV;
}
public void WriteCSV(DataRow drMeta, string outputFilePath)
{
try
{
StringBuilder sb = new StringBuilder();
int cnt = File.ReadAllLines(outputFilePath).Length;
#region write csv headers
if (cnt == 0)
{
WriteCSVHeader(drMeta, outputFilePath);
}
#endregion
#region write csv rows
foreach (DataColumn dcMeta in drMeta.Table.Columns)
{
sb.Append(FormatCSV(drMeta[dcMeta.ColumnName].ToString()) + ",");
}
#endregion
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
File.AppendAllText(outputFilePath, sb.ToString());
}
catch (Exception ex)
{
throw;
}
}
#endregion
}
}5. Output:
6. Conclusion:
If you want to read the inputs from Csv and write the output result into Csv, I guess this article helps you a lot. Hope you enjoyed reuse this article and save your valuable time.