简体   繁体   English

尝试从目录中删除文件

[英]Trying to delete a file from directory

I am trying to delete a file from a directory in an asp.net application, but I always get an exception that the file is being used by another process which is caused probably by the application itself. 我试图从asp.net应用程序中的目录中删除文件,但是我总是遇到一个例外,该文件正在由另一个进程使用,这可能是由应用程序本身引起的。

this is the code 这是代码

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();
        }
    }

how should i preform this action? 我应该如何执行此操作? thanks 谢谢

I implemented this as a part of using the OnRowDeleting method from gridview so when i delete the photo from the database it will also delete the photo from the site's folder. 我将其实现为在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();
        }
    }
}

I am more than willing to accept any other ideas for this action. 我非常愿意接受任何其他有关此操作的想法。

When you are using an object that encapsulates any resource, you have to make sure that when you are done with the object, the object's Dispose method is called. 使用封装任何资源的对象时,必须确保在处理完该对象后,调用该对象的Dispose方法。

This can be done more easily using the using statement in C#. using statement C#中的using statement可以更轻松地完成此操作。 The using statement simplifies the code that you have to write to create and then finally clean up the object. using语句简化了创建和最终清理对象所需编写的代码。 The using statement obtains the resource specified, executes the statements and finally calls the Dispose method of the object to clean up the object....... using语句获取指定的资源,执行该语句,最后调用对象的Dispose方法以清理对象。

the problem is the IIS express service that is running on my localHost. 问题是我的localHost上运行的IIS Express服务。 the process is called iisexpress.exe and it is using the file even after i close the site and try to delete it manually. 该过程称为iisexpress.exe,即使我关闭了站点并尝试手动删除它,它仍在使用该文件。 after I moved back to use the asp.net development sever the issue was gone. 我搬回使用asp.net开发服务器后,问题就消失了。 thanks for everyone. 谢谢大家

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM