Parsing CSV files
Ed Kaim points out a method to import a CSV file into a DataSet. I'm probably one of those fellows that found his site while searching Google. I went about the procedure a little bit differently. Here's what I put together:
static DataSet ReadCSV(string file)
{
if (! File.Exists(file) )
return null;
DataSet ds = new DataSet();
OleDbConnection conn = null;
string FileConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
@Path.GetDirectoryName(file) + ";" + @"Extended Properties=""Text;HDR=YES;""";
try
{
try
{
conn = new OleDbConnection();
conn.ConnectionString = FileConnection;
conn.Open();
}
catch
{
Console.WriteLine("Database connection can't be established");
return null;
}
string sql = String.Format("SELECT * FROM {0}",Path.GetFileName(file));
OleDbDataAdapter oda = new OleDbDataAdapter(sql, conn);
oda.SelectCommand.ExecuteNonQuery();
oda.Fill(ds, "TableName");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
if(conn != null)
conn.Dispose();
}
return ds;
}