简体   繁体   中英

Trying to delete an XML file throws “The process cannot access the file…” error

I have a little app that is supposed to read through an XML document that the user uploads. If the file doesn't have the proper nodes, the file is deleted and the user is notified.

However, the file is always locked when I try to delete it, both in code and through windows explorer. It stays locked until I refresh the page in IE.

myDoc.Load(FileUpload2.FileContent);
string XMLpath = Server.MapPath(ConfigurationSettings.AppSettings["PDFLocation"]) + FileUpload2.FileName;
myDoc.Save(XMLpath);
file = new FileInfo(XMLpath);

//here I check if the file is valid. If not, delete

file.Delete(); //This is where it throws the "cannot access the file" error

the full text of the error:

The process cannot access the file 'C:\project\files\file.xml' because it is being used by another process. 

I tried putting in FileUpload2.FileContent.Dispose(); and FileUpload2.Dispose(); before the delete statement, but no luck.

How do I release the file for deletion?

You need to close the file after saving it. You cannot delete the file if your application has it open.

You shouldn't save the XML file to disk at all until you know it's valid.

To answer your question, you left an open FileStream somewhere in the elided code.
You need to Dispose() it, preferably by using a using statement.

I don't know what type of myDoc is... but if it has a method " Close " or " Dispose " then call that before trying to delete...

EDIT: if it does not have such a method then myDoc = null; could help.

After saving yout file you neeed to close it as well as flush the memory.

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