上传ASP.NET后删除文件

本文关键字:删除 文件 NET ASP 上传 | 更新日期: 2023-09-27 18:03:02

我做了一个系统,用户可以将文件(图像)上传到服务器,服务器保存它。一切都很好,但是当我想删除用户上传的文件时,我得到一个异常说:

the process cannot access the file because it is being used by another process

这是保存文件的代码:

HttpFileCollection files = httpRequest.Files;
for (int i = 0; i < files.Count; i++) {
    var postedFile = files[i];
    // I tried this one before, but I read that I should .Dispose() files, therefore
    // I settled to the other, uncommented solution (however, both of them do the same thing)
    //postedFile.SaveAs(filePath);
    using (FileStream fs = File.Create(filePath)) {
        postedFile.InputStream.CopyTo(fs);
        postedFile.InputStream.Close();
        postedFile.InputStream.Dispose();
        fs.Dispose();
        fs.Close();
    }
}

删除文件很简单。在一个名为Delete的方法中,我调用了这个方法:

...
File.Delete(HttpContext.Current.Server.MapPath(CORRECT_PATH_TO_FILE));
...
对于如何解决这个问题有什么建议吗?

谢谢

上传ASP.NET后删除文件

正如Michael Perrenoud在对我的主要问题的评论中建议的那样,我也在另一个类中打开文件,并且在完成处理它时不处理它。问题就这样解决了。谢谢!

您在哪里尝试文件删除方法?作为循环的一部分?如果是这样,很自然地将其锁定。如果在循环之外,则是另一个问题(可能还没有垃圾收集?)。

为了避免循环问题,收集一个要删除的位置列表(在循环外声明,可以在循环内填充),然后在另一个"清理"循环中删除(另一种方法对可重用性更好)。

注意:Close()在Dispose()之前,而不是相反。实际上,您不必两者都做,因为Dispose()应该始终处理确保一切都是干净的(特别是在。net框架中使用IDisposable),但我不认为Close()后面跟着Dispose()有任何危害。