尝试删除 XML 文件会抛出“进程无法访问该文件...”错误
我有一个小应用程序,它应该读取用户上传的 XML 文档。如果文件没有正确的节点,则会删除该文件并通知用户。
但是,当我尝试通过代码和 Windows 资源管理器删除该文件时,该文件始终被锁定。它保持锁定状态,直到我刷新 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 process cannot access the file 'C:\project\files\file.xml' because it is being used by another process.
我尝试在删除语句之前放入 FileUpload2.FileContent.Dispose();
和 FileUpload2.Dispose();
,但没有运气。
如何释放文件以进行删除?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您知道 XML 文件有效之前,根本不应该将其保存到磁盘。
为了回答您的问题,您在删除的代码中的某处留下了一个打开的
FileStream
。您需要
Dispose()
它,最好使用using
语句。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 ausing
statement.保存后需要关闭文件。如果您的应用程序打开了该文件,则您无法删除该文件。
You need to close the file after saving it. You cannot delete the file if your application has it open.
我不知道 myDoc 是什么类型...但如果它有方法“
Close
”或“Dispose
”,则在尝试删除之前调用该方法...编辑:
如果它没有这样的方法,那么
myDoc = null;
可能会有所帮助。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.保存 yout 文件后,您需要关闭它并刷新内存。
After saving yout file you neeed to close it as well as flush the memory.