.NET应用程序锁定文件

编程入门 行业动态 更新时间:2024-10-27 09:46:42
本文介绍了.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应用程序锁定文件

本文发布于:2023-11-16 18:07:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606603.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用程序   文件   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!