Search code examples
c#asp.netfile-iogdilocked-files

Why won't GDI let me delete large images?


My ASP.NET application has an image cropping and resizing features. This requires that the uploaded temporary image be deleted. Everything works fine, but when I try to delete an image larger than 80px by 80px I get a "File is locked by another process..." error, even though I've released all resources.

Here's a snippet:

System.Drawing.Image tempimg = System.Drawing.Image.FromFile(temppath);
System.Drawing.Image img = (System.Drawing.Image) tempimg.Clone(); //advice from another forum
tempimg.Dispose();

img = resizeImage(img, 200, 200); //delete only works if it's 80, 80
img.Save(newpath);
img.Dispose();

File.Delete(temppath);

Solution

  • I think you are not disposing the first Image instance assigned to the img variable.

    Consider this instead:

    System.Drawing.Image tempimg = System.Drawing.Image.FromFile(temppath);
    System.Drawing.Image img = (System.Drawing.Image) tempimg.Clone();
    tempimg.Dispose();
    
    System.Drawing.Image img2 = resizeImage(img, 200, 200);
    img2.Save(newpath);
    img2.Dispose();
    img.Dispose();
    
    File.Delete(temppath);