views:

154

answers:

2

Okay I;m really new to VB.NET and desktop application development. Simplified this is what is happening in my application:

Dim Files() As New List(Of IO.FileInfo)
Files.Add( (New IO.FileInfo("C:\img1.jpg")) )
Files.Add( (New IO.FileInfo("C:\img2.jpg")) )
'Picture is a Windows.Forms.PictureBox in my WinForm '
Picture.Image = New System.Drawing.Bitmap(Files(0).FullName)
Picture.image = Nothing
CurrentFile = Files(0)
'Show next pic (img2)'
Files.RemoveAt(0)
Picture.Image = New System.Drawing.Bitmap(Files(0).FullName)
'Move img1 to other location '
CurrentFile.MoveTo("C:\other\img1.jpg")

The last line will throw an Exception saying that img1 cannot be moved because it is in use. So my application is still using it, but how to make my application stop locking the file? There is nothing keeping a refrence to it (as far as I see)

+3  A: 

This is because of GDI+. Look here for a solution and explanation: http://gabrielmagana.com/2009/05/c-working-with-images-image-files-and-pictureboxes/

gmagana
Your link shows a very good function. However it for some reason unvalidates EXIF data, so I used itowslon's method, taking the risk that there might be some cases where the file will remain locked.
Pim Jager
+6  A: 

The guilty party is the Bitmap. The Bitmap(string) constructor does result in the Bitmap holding a lock on the file until the Bitmap is disposed. See the remarks in the docs:

The file remains locked until the Bitmap is disposed.

To fix the problem, either dispose the Bitmap (if you have finished with it), or manually load the bytes from the file into a MemoryStream from the file and load the Bitmap from the MemoryStream. (Again, the Bitmap(Stream) constructor requires the Stream to remain open, so you can't get away with just creating a FileStream over the file; you need to load the bytes into memory, and keep the MemoryStream around until you have finished with the Bitmap.)

itowlson
Even disposing does not work sometimes. GDI+ maintains the lock on the file, and you cannot deterministically control that lock. I tried and it was a pain in the ass to work around it.
gmagana