Delete a picture file after Bitmap.FromFile call.

Hello,

I'm loading a bitmap from a temp file using Bitmap.FromFile. After this I want to delete the file, but get an IO exception "... this file is used by a process ...". The file is used from my C# process (found with the processexplorer), so my guess is the Bitmap.FromFile call.

How do I release the file lock to delete the file

Thanks for help.

BerW



Answer this question

Delete a picture file after Bitmap.FromFile call.

  • simon_

    You should use either Bitmap.Dispose or create a clone of the bitmap and dispose the source. It should work...
  • kkmick

    Actually, if performance matters it would be better to read the file "by hand" and use Bitmap.LockBits to fill in the data - this way you avoid having 2 copies of the image.
  • Greg_Dodd

    Hmm,

    sound like overkill to create a Bitmap twice, only to get rid of the file lock.

    Is this a bug in the Bitmap.FromFile() function


  • NigelP

    Update:

    Now I tried the 2 suggested solutions. Disposing the bitmap frees also the lock of the picture file and I can delete the file.

    But Clone() also clones the file lock :-(((

    Here is the test code:

    Image bm = Bitmap.FromFile(fn);

    Image bm2 = (Image)bm.Clone();

    bm.Dispose();

    File.Delete(fn);

    The original Bitmap is disposed only the close ist alive, but still get the Exception ...

    Any other solutions

    BerW


  • LamptonWorm

    So create a new bitmap object and draw it using Graphics.FromImage, Graphics.DrawImageUnscaled
  • Delete a picture file after Bitmap.FromFile call.