Below is the method to save the data from Dataset to file named OrderData.csv
public void WriteOrderData(DataSet ds)
{
try
{
string path = "~/Error/" + "OrderData" + ".csv";
// if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
// {
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
//}
using (StreamWriter sw = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
DataTable dt = ds.Tables[0];
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Write Table Rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
} sw.Close();
}
////save dialog box
String filePath = System.Web.HttpContext.Current.Server.MapPath("Error/OrderData.csv");
System.IO.FileInfo targetFile = new FileInfo(filePath);
if (targetFile.Exists)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + targetFile.Name);
HttpContext.Current.Response.AddHeader("Content-Length", targetFile.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(targetFile.FullName);
}
}
catch (Exception ex)
{
WriteError(ex.Message);
}
}
No comments:
Post a Comment