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 can开发者_如何学编程not 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 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.
You need to close the file after saving it. You cannot delete the file if your application has it open.
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.
精彩评论