2

我试图从 asp.net 应用程序的目录中删除一个文件,但我总是得到一个异常,即该文件正在被另一个进程使用,这可能是由应用程序本身引起的。

这是代码

TableCell cell = (TableCell)PhotoGalleryGridView.Rows[e.RowIndex].Cells[1];
    DirectoryInfo photoGalleryDirectory = new DirectoryInfo(Server.MapPath("~/GalleryImages/"));
    FileInfo[] imgFiles = photoGalleryDirectory.GetFiles();
    for (int i = 0; i < imgFiles.Length; i++)
    {
        if (imgFiles[i].Name == cell.Text)
        {
            imgFiles[i].Delete();
        }
    }

我应该如何执行此操作?谢谢

我将其实现为使用 gridview 中的 OnRowDeleting 方法的一部分,因此当我从数据库中删除照片时,它也会从站点文件夹中删除照片。

protected void PhotoGalleryGridView_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{

    TableCell cell = (TableCell)PhotoGalleryGridView.Rows[e.RowIndex].Cells[1];
    DirectoryInfo photoGalleryDirectory = new DirectoryInfo(Server.MapPath("~/GalleryImages/"));
    FileInfo[] imgFiles = photoGalleryDirectory.GetFiles();
    for (int i = 0; i < imgFiles.Length; i++)
    {
        if (imgFiles[i].Name == cell.Text)
        {
            imgFiles[i].Delete();
        }
    }
}

对于此操作,我非常愿意接受任何其他想法。

4

2 回答 2

1

当您使用封装任何资源的对象时,您必须确保当您使用完该对象时,调用该对象的 Dispose 方法。

这可以使用using statementC# 中的 更轻松地完成。using 语句简化了您必须编写的代码,以创建并最终清理对象。using语句获取指定的资源,执行语句,最后调用对象的Dispose方法清理对象......

于 2012-03-18T10:41:42.263 回答
0

问题是在我的 localHost 上运行的 IIS express 服务。该过程称为iisexpress.exe,即使在我关闭站点并尝试手动删除它之后,它仍在使用该文件。在我搬回去使用 asp.net 开发服务器后,问题就消失了。谢谢大家。

于 2012-03-19T08:30:20.287 回答