简体   繁体   中英

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

I'm trying to read an Excel file, view it on a table and then save the data into a database. However, whenever I try importing the same file again I keep getting the IOException. I am almost sure the process that is accessing the file is my own program. What am I missing and what should I do?

I was trying to closing the file as it may still be open, however was not so sure about how that should be done.

Here is where I get the exception:

 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);

Is it possible that the code is working too fast and is unable to delete the item before it can be saved again?

To test this, put a sleep in your code like this:

System.IO.File.Delete(path); Threading.Thread.Sleep(500) excelfile.SaveAs(path);

If this works then it's recommended that you swap away from the sleep function as it causes the application to freeze whilst it is sleeping.

Edit: I realised the last part may be unclear: switch from the Theading.Thread.Sleep(Time in ms) to something like a hidden timer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM