1. Read in your .csv properly. Take into account that the file can be written in any codepage and if you have to repeat the operation for files from several sources, make sure you can configure the separator.
2. Convert your data and store it in a DataTable. This is very convenient if you want to manipulate your data, or preview it, in for example a DataGridView. Afterwards you can also easily transfer the DataTable to a database with ADO.
3. Possible additions to the code: you could configure the datatype of the columns to be created, add extra logic to avoid adding invalid data etc. Anyway, here's a start. I hope it helps,
Regards,
Joachim
// Make sure you have these:
using System.Data;
using System.IO;
/// <summary>
/// Reads in a .csv file.
/// </summary>
/// <param name="fileName">File path.</param>
/// <param name="encoding">Encoding in which the file is written.</param>
/// <param name="separator">The separator used to separate the fields</param>
/// <returns></returns>
public static DataTable ReadFromCsv(string fileName, Encoding encoding, char separator)
{
DataTable table = null;
if (fileName != null &&
!fileName.Equals(string.Empty) &&
File.Exists(fileName))
{
try
{
// If required, you can collect some useful info from the file
FileInfo info = new FileInfo(fileName);
string tableName = info.Name;
// Prepare for the data to be processed into a DataTable
// We don't know how many records there are in the .csv, so we
// use a List<string> to store the records in it temporarily.
// We also prepare a DataTable;
List<string> rows = new List<string>();
// Then we read in the raw data
StreamReader reader = new StreamReader(fileName, encoding);
string record = reader.ReadLine();
while (record != null)
{
rows.Add(record);
record = reader.ReadLine();
}
// And we split it into chuncks.
// Note that we keep track of the number of columns
// in case the file has been tampered with, or has been made
// in a weird kind of way (believe me: this does happen)
// Here we will store the converted rows
List<string[]> rowObjects = new List<string[]>();
int maxColsCount = 0;
foreach (string s in rows)
{
string[] convertedRow = s.Split(new char[] { separator });
if (convertedRow.Length > maxColsCount)
maxColsCount = convertedRow.Length;
rowObjects.Add(convertedRow);
}
// Then we build the table
table = new DataTable(tableName);
for (int i = 0; i < maxColsCount; i++)
{
// Change this if you want other datatypes
// make sure you also convert the string[] to
// the corect datataype
table.Columns.Add(new DataColumn());
}
foreach (string[] rowArray in rowObjects)
{
table.Rows.Add(rowArray);
}
table.AcceptChanges();
}
catch
{
throw new Exception("Error in ReadFromCsv: IO error.");
}
}
else
{
throw new FileNotFoundException("Error in ReadFromCsv: the file path could not be found.");
}
return table;
}
|