File.Delete被另一个进程使用

时间:2015-10-02 23:43:06

标签: c# asp.net

文件删除问题 - 请帮助我,我不能删除文件..当我尝试删除我得到这个按摩

  

c#File.Delete - 另一个进程使用的文件#File.Delete -   另一个进程正在使用的文件

    protected void Button2_Click1(object sender, EventArgs e)
{

    HttpFileCollection hfc = Request.Files;
    string x = "";
    string foldername = DateTime.Now.ToString().Trim().Replace(" ", "").Replace(":", "").Replace("/", "");
    string foldername1 = foldername+"1";
    Directory.CreateDirectory(Server.MapPath("~/IMAGEUPLOADCENTER/") + foldername);
    Directory.CreateDirectory(Server.MapPath("~/IMAGEUPLOADCENTER/") + foldername1);
    for (int i = 0; i < hfc.Count; i++)
    {
        HttpPostedFile hpf = hfc[i];
        if (hpf.ContentLength > 0)
        {
            string name =(DateTime.Now.ToString() + i + hpf.FileName).ToString().Trim().Replace(" ", "").Replace(":", "").Replace("/", "");
            hpf.SaveAs(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name);
            ResizeImageWidth(497, Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name, Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);
            System.Drawing.Image upImage = System.Drawing.Image.FromFile(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);  //System.Drawing.Image.FromStream(FU1.PostedFile.InputStream);
            System.Drawing.Image logoImage = System.Drawing.Image.FromFile(Server.MapPath("~/pages002248Xc54/UploadImages/LOGOnew.png"));
            using (Graphics g = Graphics.FromImage(upImage))
            {
                g.DrawImage(logoImage, new Point(upImage.Width - logoImage.Width - 10, 10));
                upImage.Save(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name);
                File.Delete(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);
             //   Image1.ImageUrl = "~/UploadFiles/2" + "//" + fileName;
            }
            x = x + "</br><img src='http://hela.co.il/IMAGEUPLOADCENTER/" + foldername + "/" + name + "'/></br>";
        }
    }
    TextArea1.InnerText = x;
    FileUpload1.Visible = false;
    Button2.Visible = false;
}

1 个答案:

答案 0 :(得分:3)

您的文件被您锁定,这阻止您删除它。 Image.FromFile方法锁定用于创建对象的文件,直到处理Image对象为止。因此,在这种情况下,图像文件将保持锁定状态,直到您处理upImage。

将File.Delete移动到完成图像后,它将起作用。在下面的代码中,我为每个变量添加了使用语句,以便它们将被处理掉(并解锁文件),然后我将delete语句移到using块之外(在处理Image对象之后)。

using(System.Drawing.Image upImage =  System.Drawing.Image.FromFile(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name))     
using(System.Drawing.Image logoImage = System.Drawing.Image.FromFile(Server.MapPath("~/pages002248Xc54/UploadImages/LOGOnew.png")))
using (Graphics g = Graphics.FromImage(upImage))
{
    g.DrawImage(logoImage, new Point(upImage.Width - logoImage.Width - 10, 10));
    upImage.Save(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name);
}
File.Delete(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);

Image.FromFile Method (String)

using statement (C#)