»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 CSVThis 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;
}
} |
|