Home | Articles|Namespace|Interview Questions|Tools|Jobs|Projects|Community
Asp.net Tutorials

»Dotnet Ads
»Message Boards
Message Boards
Dotnet Books

»Member Details
Register
Login
LogOut
Submit Code
Submit Jobs
Submit Projects

»Competition
Community
Winners
Prizes
Write For Us
Members

»Other Resources
Links
Dotnet Resources

Create Data Table from CSV

This function creates a DataTable from a CSV file.
public static DataTable ConvertCsvToDatatable(string filePath)
{
if (! File.Exists(filePath) )
throw new Exception("File does not exist.");


OleDbDataAdapter oda = null;
OleDbConnection conn = null;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
Path.GetDirectoryName(filePath) + ";" + "Extended Properties=\"Text;HDR=YES;Imex=1\"";


DataTable dt = new DataTable("mytable");

try
{
try
{
conn = new OleDbConnection();
conn.ConnectionString = strConn;
conn.Open();
}
catch //(Exception ex)
{
throw;
//Console.WriteLine("Database connection can't be established");
//return null;
}
string sql = String.Format("SELECT * FROM [{0}]",Path.GetFileName(filePath));
oda = new OleDbDataAdapter(sql, conn);
oda.SelectCommand.ExecuteNonQuery();
oda.Fill(dt);
return dt;
}
catch //(Exception ex)
{
throw;
//Console.WriteLine(ex.Message);
//return null;
}
finally
{
strConn = null;
if(dt != null) dt.Dispose();
dt = null;
if(oda != null) oda.Dispose();
oda = null;
if(conn != null) conn.Dispose();
conn = null;
}
}

Have a Question and dont know the answer post it below and get answers in minutes

Due to spam this feature is disabled
To get answers fast , make sure you enter a detailed subject for example: "DataGrid issues need answer" not "DataGrid"

Subject:

Catjegory Name:

Message:



© 2008 dotnetwatch.com -- Privacy policy