文件.删除正在被其他进程使用的内容

本文关键字:进程 其他 删除 文件 | 更新日期: 2023-09-27 18:15:59

文件删除问题-请帮助我,我不能删除文件。当我试图删除时,我得到了这个消息

c#文件。删除-文件正在被另一个进程c#文件使用。删除- - - - - -文件正在被其他进程使用

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

文件.删除正在被其他进程使用的内容

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

移动文件。删除后,你完成与图像,它将工作。在下面的代码中,我向每个变量添加了using语句,这样它们就会被释放(并解锁文件),然后我将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);

形象。FromFile Method (String)