Image saved as File is locked

J

JezB

I have an Image object (i) which I want to write to a file. This does work
but when I later try to do something with this file I get errors, because I
think the file is still 'locked'. I have to restart the application before
the locks are released. I tried it first as:

Image i = ... ; // correctly instantiated to some image
i.Save("image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
// later errors doing something with image.jpg

Then I tried cloning the image before I write to the file, and disposing of
both images after the file is written:

Image i = ... ; // correctly instantiated to some image
Image ii = (Image)i.Clone();
ii.Save("image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
ii.Dispose();
i.Dispose();
// later errors doing something with image.jpg

but STILL I'm getting the errors. I'm not sure if the lock is on the file or
the image it was based on. Anyone know what the problem can be and how to
get round it ?
 
N

Nicholas Paldino [.NET/C# MVP]

JezB,

Instead of using the Save overload which takes the file, I would create
a FileStream which you open for write access and then pass that to the Save
method. The Save method that takes the name of a file will open the file
exclusively, and until it is disposed, it doesn't let go of the FileStream
which it used to open the file exclusively.

Hope this helps.
 
J

JezB

Thanks for the suggestion. Changed it to:

Image i = ... ; // correctly instantiated to some image
using (FileStream fs = new FileStream("image.jpg",FileMode.Create))
{
i.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
i.Dispose();
fs.Close();
}

but the file still seems to be locked. Anything I've missed?
 
J

JezB

Sorry, that may turn out not to be true. The image I was trying this out on
happened to be in PNG format, though I was saving it as JPG !
 
N

Nicholas Paldino [.NET/C# MVP]

JezB,

Are you sure you don't have the file open anywhere else? The using
statement is guaranteeing that the FileStream is disposed of properly, and
shouldn't keep the file locked.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top