Populate Dataset from CSV Delimited File

While searching and searching for the best method of importing a comma delimited file into a dataset, I ran across this blog: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=6015&SiteID=1 . This code is great, before locating this post, I had almost written a whole page of code with three methods. Not including the code written before hand where as I was attempting to first convert the csv file to xml from within code, and before that reading the file to a data table. This code made life a lot easier, link to blog located above. I also added a method for saving file locally and naming it, also going back after file read into data set and deleting file.


string FileName = SaveFile(File, ".csv");
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + Path.GetDirectoryName(FileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + Path.GetFileName(FileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
this.InventoryFile = ds.Tables[0];
conn.Close();
System.IO.File.Delete(FileName);


//Save File and Name
protected string SaveFile(byte[] bytes, string PassFileExtention)
{

try
{
string DestDirectory = config.GetStringValue("", "CustomBoxTempDirectory", "");

if (DestDirectory[DestDirectory.Length - 1] != '\\')
DestDirectory = DestDirectory + "\\";

if (!Directory.Exists(DestDirectory))
Directory.CreateDirectory(DestDirectory);

MemoryStream plainStream = new MemoryStream(bytes);
FileStream SaveFileSteam;
string FileName = DestDirectory + "CustomBoxUpload" + this.AssociateID + PassFileExtention;

try
{
//Make sure this file does not exist before we save off the next one.
System.IO.File.Delete(FileName);
}
catch { }
try
{
SaveFileSteam = System.IO.File.Create(FileName);
}
catch
{
System.IO.File.Delete(FileName);
SaveFileSteam = System.IO.File.Create(FileName);
}

plainStream.WriteTo(SaveFileSteam);
SaveFileSteam.Close();
return FileName;
}
catch
{
return null;
}
}

Comments

Post a Comment