views:

67

answers:

2

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 other process..." error, even though I've released all resources.

Can anyone help? I'm tired of Googling!

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);
+1  A: 

If you create the image this way, it won't be locked:

using (FileStream fs = new FileStream(info.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    byte[] data = new byte[fs.Length];
                    int read = fs.Read(data, 0, (int)fs.Length);
                    MemoryStream ms = new MemoryStream(data, false);
                    return Image.FromStream(ms, false, false); // prevent GDI from holding image file open
                }
codymanix
This code is not correct. The documentation for Image.FromStream states "You must keep the stream open for the lifetime of the Image." The above code does not do that. And, if it did do that, the file would remain locked.
binarycoder
I edited my answer. Now you have a stream which remains open and the file won't be locked.
codymanix
+1  A: 

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);
binarycoder
+1: Well spotted! I missed that completely.
RichieHindle
Wow ! Thanks a million- works now ! I had actually given up...sometimes the most defficult questions are the simplest!
The_AlienCoder