.NET应用程序锁定文件 [英] .NET app locks file

查看:124
本文介绍了.NET应用程序锁定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我,真的很新VB.NET和桌面应用程序的开发。简化这就是发生在我的应用程序:

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

最后一行将抛出一个异常说IMG1不能移动,因为它正在使用中。所以我的应用程序仍然使用它,但如何让我的应用程序停止锁定的文件?没有什么保持refrence它(据我看到的)

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)

推荐答案

有罪的一方是位图。该位图(串)构造并导致位图持有的文件锁,直到位图设置。看到文档的备注:

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.

要解决这个问题,无论是处理位图(如果你完成它),或手动加载的文件中的字节到从文件中一个MemoryStream并加载从MemoryStream的位图。 (同样,位图(流)构造要求流保持开放,所以您不能逃脱只创建一个FileStream过文件,你需要加载字节到内存中,并围绕保持MemoryStream的,你已经完成了位图到。)

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

这篇关于.NET应用程序锁定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆