The process cannot access the file because it is being used by another process – using static class

I get the error “The process cannot access the file because it is being used by another process” when I attempt to delete the files I just uploaded (this is at least a few seconds after the files were uploaded, so I am sure they are finished writing). Any ideas why this occurs? PS: The thumbnails I generate delete without a problem, but the originals are locked somehow.

            var FileExt = Path.GetExtension(photo.File.FileName);
            var FilePath = Path.Combine(Server.MapPath("~/App_Data/" + photo.ClientId), photo.PhotoId.ToString()) + FileExt;
            photo.File.SaveAs(FilePath);
            var ThumbFilePath = Path.Combine(Server.MapPath("~/App_Data/" + photo.ClientId),photo.PhotoId.ToString() + "_thumbnail") + FileExt;
            PhotoTools.MakeThumbnail(FilePath, ThumbFilePath, 0.15);
            return RedirectToAction("Create");

Inside a PhotoTools class…

    public static void MakeThumbnail(string ImgIn, string ImgOut, double Percent)
    {
        Image img = Image.FromFile(ImgIn);
        double Width = img.Width*Percent;
        double Height = img.Height*Percent;
        MakeThumbnail(ImgIn, ImgOut, (int)Width, (int)Height);
    }

Delete function…

    public ActionResult DeleteConfirmed(int id)
    {
        Client client = db.Clients.Find(id);
        db.Clients.Remove(client);
        db.SaveChanges();
        if (Directory.Exists(Server.MapPath("~/App_Data/" + id)))
        {
            Directory.Delete(Server.MapPath("~/App_Data/") + id,true);
        }
        return RedirectToAction("Index");
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In your MakeThumbnail methods, make sure you’re calling Dispose() on the Image types. That or use the using syntax:

using (Image img = Image.FromFile(ImgIn))
{
    // Your code
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x