如何从上传的文件夹中删除存在的Excel文件?

时间:2015-07-10 10:18:48

标签: c#

如何关闭Excel文件或从文件夹中删除。我尝试了很多,但它没有得到文件。所以总是抛出错误:进程无法访问该文件,因为它被另一个进程使用。如何解决?

第一次没有抛出任何错误。上传成功上传,但下次使用相同的文件时我试图上传然后在调用上传方法之前发送错误 创建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();
                    }

检查文件

string FileName = "Customer_Creation";
                string Paths = Server.MapPath("~/Uploads/") + FileName;
                FileInfo file = new FileInfo(Paths);
                if (file.Exists)
                {
                    file.Delete();
                }

上传活动点击

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";
            }
        }

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

现在很难说出了什么问题。您的文件很可能仍在程序的某些部分中使用。请检查 this link ,其中包含有关如何调试它的有用信息。

您的应用已将文件上传到服务器。为此,它使用托管资源(如FileStream等)。由于某种原因,此文件仍保持打开稍后您的应用会尝试在仍在使用时将其删除。你得到这个“正在使用的文件”例外。

我建议您尝试直接删除此文件,如果这样可行,则问题会隐藏在代码“上传部分”的某处。如果不是那么问题很可能就在于使用这个文件的一些外部进程。