C # Free image file from use

I have a temp image file that I open with

Bitmap CapturedImg = (Bitmap)Image.FromFile("Item/Item.bmp"); 

and because temp I want to replace it with another image for future use, but the program still uses this image, and I can not do anything.

How to refuse an image for replacement?

+4
source share
5 answers

I had a similar problem and could not use it because the file was overwritten by some asynchronous code. I solved the problem by making a copy of Bitmap and freeing the original:

  Bitmap tmpBmp = new Bitmap(fullfilename); Bitmap image= new Bitmap(tmpBmp); tmpBmp.Dispose(); 
+2
source

From MSDN

The file remains locked until the image is located.

Reading image from file stream instead

 using( FileStream stream = new FileStream( path, FileMode.Open, FileAccess.Read ) ) { image = Image.FromStream( stream ); } 
+2
source

Try using this syntax

 using (Bitmap bmp = (Bitmap)Image.FromFile("Item/Item.bmp")) { // Do here everything you need with the image } // Exiting the block, image will be disposed // so you should be free to delete or replace it 
+1
source
 using (var stream = System.IO.File.OpenRead("Item\Item.bmp")) { var image= (Bitmap)System.Drawing.Image.FromStream(stream) } 
0
source

You can also try this.

  BitmapImage bmpImage= new BitmapImage(); bmpImage.BeginInit(); Uri uri = new Uri(fileLocation); bmpImage.UriSource = uri; bmpImage.CacheOption = BitmapCacheOption.OnLoad; bmpImage.EndInit(); return bmpImage; 
0
source

All Articles