The situation:
You have uploaded a CSV file, and you now need to do something with the data in your programming.
A Solution:
using System.Data;
using System.Data.OleDb;
using System.IO;
public static DataTable ParseCSV(string path, bool headerinfile)
{
if ( !File.Exists(path) )
return null;
string headertext = "No";
if ( headerinfile )
{
headertext = "Yes";
}
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
//create the "database" connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"text;HDR=" + headertext + ";FMT=Delimited\"";
//create the database query
string query = "SELECT * FROM " + file;
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
try
{
//fill the DataTable
dAdapter.Fill(dTable);
}
catch ( InvalidOperationException /*e*/)
{ throw; }
dAdapter.Dispose();
return dTable;
}
Pingback: How To Get Values from a DataTable without Crashing if a Column Doesn’t Exist « The Self-Taught Programmer