尝试删除 XML 文件会抛出“进程无法访问该文件...”错误

发布于 2024-11-25 12:31:50 字数 769 浏览 0 评论 0原文

我有一个小应用程序,它应该读取用户上传的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

菊凝晚露 2024-12-02 12:31:50

在您知道 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 a using statement.

绻影浮沉 2024-12-02 12:31:50

保存后需要关闭文件。如果您的应用程序打开了该文件,则您无法删除该文件。

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

任谁 2024-12-02 12:31:50

我不知道 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.

梦言归人 2024-12-02 12:31:50

保存 yout 文件后,您需要关闭它并刷新内存。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文