删除asp.net中的文件(FileInfo)

时间:2009-09-11 09:23:28

标签: asp.net

在我的页面中。当我上传图像我做了图像管理。之后,我想删除原始图像,但我收到文件已经在使用的错误,如下所示 (进程无法访问文件'D:\ sasiweb \ myimage \ Images \ jalsa.jpeg',因为它正由另一个进程使用。)

这是我的代码

protected void sizeManage(string filename)     {

    string fn = Server.MapPath("~/Images/" + filename );

    System.Drawing.Bitmap newimg = new System.Drawing.Bitmap(fn);
    int h = newimg.Height;
    int w = newimg.Width;

    if (w > 100)
    {
        objJpeg = new ASPJPEGLib.ASPJpeg();
        objJpeg.Open(Server.MapPath("~/Images/" + FileUpload1.FileName.ToString()));

        int L = 100;
        objJpeg.Width = L;

        objJpeg.Height = objJpeg.OriginalHeight * L / objJpeg.OriginalWidth;
        objJpeg.Save(Server.MapPath("~/Images/" + "small" + FileUpload1.FileName));

        string path = Server.MapPath("~/Images/" + FileUpload1.FileName.ToString());
        FileInfo file = new FileInfo(path);
        file.Delete();


    }
    else
    {

    }


}


protected void Button1_Click(object sender, EventArgs e)
{

    FileUpload1.SaveAs(Server.MapPath("~/Images/" + FileUpload1.FileName.ToString()));
    sizeManage(FileUpload1.FileName.ToString());

}

我在file.delete();

收到错误

(进程无法访问文件'D:\ sasiweb \ myimage \ Images \ jalsa.jpeg',因为它正由另一个进程使用。)

3 个答案:

答案 0 :(得分:2)

你必须关闭

objJpeg

执行此操作。

由于使用objJpeg对象打开文件,因此必须释放它以删除文件。

string path = Server.MapPath("~/Images/" + FileUpload1.FileName.ToString());
FileInfo file = new FileInfo(path);

objJpeg.Close(); // release the resources held by the object
file.Delete();

或者您可以在using语句中编写文件打开过程。

答案 1 :(得分:1)

ASPJPEGLib.ASPJpeg()是否实现了IDisposable?如果确实如此,则应在保存后进行处理。最简单的方法是将它包装在Using语句中,例如。

        using (objJpeg = new ASPJPEGLib.ASPJpeg())
        {
           objJpeg.Open(Server.MapPath("~/Images/" + FileUpload1.FileName.ToString()));

           int L = 100;
           objJpeg.Width = L;

           objJpeg.Height = objJpeg.OriginalHeight * L / objJpeg.OriginalWidth;
           objJpeg.Save(Server.MapPath("~/Images/" + "small" + FileUpload1.FileName));
        }

        string path = Server.MapPath("~/Images/" + FileUpload1.FileName.ToString());
        FileInfo file = new FileInfo(path);
        file.Delete();

答案 2 :(得分:0)

您必须关闭该文件 ...

    objJpeg.Save(Server.MapPath("~/Images/" + "small" + FileUpload1.FileName));
    objJpeg.Close();
    string path = Server.MapPath("~/Images/" + FileUpload1.FileName.ToString());

...