![](/img/trans.png)
[英]“the process cannot access the file because it is being used by another process” when trying to delete file
[英]Trying to delete a saved Excel file but getting the IOException: The process cannot access the file because it is being used by another process
我正在尝试读取Excel文件,在表上查看它,然后将数据保存到数据库中。 但是,每当我尝试再次导入同一文件时,我都会不断得到IOException。 我几乎可以肯定,访问文件的过程是我自己的程序。 我想念什么,我该怎么办?
我试图关闭该文件,因为它可能仍处于打开状态,但是对于如何完成该操作并不确定。
这是我得到异常的地方:
if(excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/Content/" + excelfile.FileName);
if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
excelfile.SaveAs(path);
代码是否可能工作太快并且无法删除项目,然后才能再次保存?
要测试这一点,请像下面这样在代码中入睡:
System.IO.File.Delete(path); Threading.Thread.Sleep(500) excelfile.SaveAs(path);
如果这行得通,那么建议您从睡眠功能中退出,因为它会使应用程序在睡眠时冻结。
编辑:我意识到最后一部分可能还不清楚:从Theading.Thread.Sleep(Time in ms)
为Theading.Thread.Sleep(Time in ms)
切换到类似隐藏的计时器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.