Alternative for Image.FromFile() without locking file

Viewed 64

The problem seems to be already known with the handling of Image(s). I want to read a Image without locking it. Through various other questions (ex. question), I have found various workarounds. Something that works for many is to save the image using a bitmap ex:

         if (new FileInfo(openImageDialog.FileName).Exists) {
               Image tmp = Image.FromFile(openImageDialog.FileName);
               pictureBoxImage.Image = new Bitmap(tmp);
               tmp?.Dispose();
         }

My problem with this is that I want to display a png with transparency, which is clearly lost with a bitmap.

Can someone come to my rescue?

1 Answers

Create your file stream explicitly and use Image.FromStream instead, allowing you to specify FileShare-mode:

using var fs = File.Open(openImageDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
Image tmp = Image.FromStream(fs);

You could allow FileShare.ReadWrite, but that might not be a good idea since things will likely break if someone is concurrently writing to the same file.

I'm not sure what problem you are describing with regards to transparency. .Net Bitmaps support transparency just fine, .bmp files do not, but you can save and load png files using the Bitmap or Image classes. I'm also unsure what transparency has to do with file locking.

Related