1

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";
            }
        }
Dawood Abbas
  • 222
  • 2
  • 12
  • so where to write wb.close()? – Dawood Abbas Jul 10 '15 at 10:25
  • there is not have any 'close()' method for wb. – Dawood Abbas Jul 10 '15 at 10:27
  • Could you please add here rest of your code – Fabjan Jul 10 '15 at 10:29
  • @Fabjan I updated it above please check there. – Dawood Abbas Jul 10 '15 at 10:35
  • 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 – Dawood Abbas Jul 10 '15 at 10:37
  • What if you upload file first then restart your application and try to upload it again ? Will it throw an exception? It looks like your file is still accessed somewhere in your code when you try to delete it. That's why it throws an exception. – Fabjan Jul 10 '15 at 10:41
  • when i upload it first time there not getting any error but when i uploading same file name then throwing an error. when i checked upload folder there all files saving where i tried to delete it by above code. – Dawood Abbas Jul 10 '15 at 11:08
  • Use the code from this answer:http://stackoverflow.com/a/1263609/1124494 to close all processes using that file. – Aishwarya Shiva Jul 10 '15 at 11:33

2 Answers2

1
I believe you just want to create a file, download it and then delete it once it has downloaded.

1. Create a custom FileHttpResponseMessage.


      public class FileHttpResponseMessage : HttpResponseMessage
        {
            private readonly string filePath;

            public FileHttpResponseMessage(string filePath)
            {
                this.filePath = filePath;
            }

            protected override void Dispose(bool disposing)
            {
                base.Dispose(disposing);
                Content.Dispose();
               if(File.Exist(filePath))
                File.Delete(filePath);
           }
        }

2. Create a function which will return generated file path. and use that path in below code :  

public HttpResponseMessage Get()
    {
        var filePath = GetNewFilePath();//your function which will create new file.
        var response = new FileHttpResponseMessage(filePath);
        response.StatusCode = HttpStatusCode.OK;
        response.Content = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName ="YourCustomFileName"
        };
        return response;
    }

3. Above code will delete file automatically once file will be served to user.
Rahul Garg
  • 4,069
  • 1
  • 34
  • 31
  • Please mark it as answer if it fulfills what you were searching for. – Rahul Garg Jul 10 '15 at 12:39
  • where to create 'FileHttpResponseMessage' class because in my form i created it then throwing error: The type or namespace name 'HttpResponseMessage' could not be found (are you missing a using directive or an assembly reference?) – Dawood Abbas Jul 15 '15 at 04:57
  • The code is posted is working code for MVC application but I now see that you are using web forms. You just need to follow same pattern and delete file just after Response.Flush(). Your code should be like this : Response.Flush(); System.IO.File.Delete(Server.MapPath("~/uploads/Customer_Creation"); Response.End(); – Rahul Garg Jul 15 '15 at 09:57
0

Right now it's difficult to say what is wrong. Most likely your file is still in use by some part of your program. Pleases check this link it contains useful information about how to debug it.

Your app has uploaded a file to a server. For this purpose it used managed resources (like FileStream etc). For some reason this file remains opened. Later your app tries to delete it when it's still in use. And you get this "File in use" exception.

What i'd recommend to do is try to delete this file directly and if this works then the problem is hidden somewhere in your 'upload part' of your code. If its not then problem is most likely lay with some external processes that uses this file.

Community
  • 1
  • 1
Fabjan
  • 13,506
  • 4
  • 25
  • 52