Rachel Morris
Rachel Morris

Reputation: 127

The process cannot access the file because it is being used by another process asp.net c#?

I am trying to delete an image from a junk folder after uploading and resizing the image to my server folder. But then I am receiving this message which is not letting me delete the image from the junk folder. How do I resolve this issue?

if (FileUpload1.HasFile)
{
    long fileSize = FileUpload1.FileContent.Length;
    double sizeinBytes = fileSize * 0.001;
    FileUpload1.SaveAs(Server.MapPath("~/junk/" + FileUpload1.FileName));
    string filepath = Server.MapPath("~/junk/" +FileUpload1.FileName);

    System.IO.FileStream fs = System.IO.File.OpenRead(filepath);
    byte[] data = new byte[fs.Length];
    fs.Read(data, 0, data.Length);

    System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
    System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
    Bitmap resizedimage = ResizeImage(image, 500, 500);
    resizedimage.Save(Server.MapPath("~/images/" + FileUpload1.FileName + ".jpeg"));
    Image1.ImageUrl = "~/images/" + FileUpload1.FileName;
    var filePath = Server.MapPath("~/junk/" + FileUpload1.FileName);
    if (File.Exists(filePath))
    {
        File.Delete(filePath);
    }
}

Upvotes: 1

Views: 737

Answers (2)

Basvo
Basvo

Reputation: 156

if (FileUpload1.HasFile)
            {
                long fileSize = FileUpload1.FileContent.Length;
                double sizeinBytes = fileSize * 0.001;
                FileUpload1.SaveAs(Server.MapPath("~/junk/" + FileUpload1.FileName));
                string filepath = Server.MapPath("~/junk/" + FileUpload1.FileName);

                using (System.IO.FileStream fs = System.IO.File.OpenRead(filepath))
                {
                    byte[] data = new byte[fs.Length];
                    fs.Read(data, 0, data.Length);

                    System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
                    System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                    Bitmap resizedimage = ResizeImage(image, 500, 500);
                    resizedimage.Save(Server.MapPath("~/images/" + FileUpload1.FileName + ".jpeg"));
                }
                Image1.ImageUrl = "~/images/" + FileUpload1.FileName;
                var filePath = Server.MapPath("~/junk/" + FileUpload1.FileName);
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }

Upvotes: 0

Dimitris Michailidis
Dimitris Michailidis

Reputation: 449

You have to encapsulate your Filestream like below, so that it gets disposed when finished:

using(FileStream fs = System.IO.File.OpenRead(filepath))
{
   //do stuff
}

//delete

Upvotes: 3

Related Questions