How to close excel file or delete from folder. I tried a lot but its not getting file there.so always throwing error : The process cannot access the file because it is being used by another process.How to solve it?
first time not throwing any error .going successfully uploaded but when next time with same file i am trying to upload then imideatly throwing an error before call upload method creating excel
System.Data.DataTable dtexcel = new System.Data.DataTable();
dtexcel = BindComboWithParm("Get_Cols_Forexcelsheet");
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dtexcel, "Customer");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Customer_Creation.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
checking for file
string FileName = "Customer_Creation";
string Paths = Server.MapPath("~/Uploads/") + FileName;
FileInfo file = new FileInfo(Paths);
if (file.Exists)
{
file.Delete();
}
upload event click
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
string FileName = "Customer_Creation";
string Paths = Server.MapPath("~/Uploads/") + FileName;
FileInfo file = new FileInfo(Paths);
if (file.Exists)
{
file.Delete();
}
if (FileUpload1.HasFile)
{
string excelPath = Server.MapPath("~/Uploads/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
ImporttoSQL(excelPath);
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(System.Web.UI.Page), "ClientScript", "alert('Please select Excelsheet')", true);
return;
}
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Exception Message: " + ex.Message.Replace("'", "").Replace("\"", "") + "');", true);
}
finally
{
ViewState["ExcelUploaded"] = "false";
}
}