开发者

.NET app locks file

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? The开发者_JAVA技巧re is nothing keeping a refrence to it (as far as I see)


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.)


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜