[英]File.Delete on bitmap doesn't work because the file is being used by another process (I used bitmap.Dispose();)
I'm creating a Windows Forms Application in C#. 我正在用C#创建Windows窗体应用程序。
I have some buttons on the form and I used the BackgroundImage
property to set bitmap images on them. 我在窗体上有一些按钮,并使用
BackgroundImage
属性在它们上设置位图图像。
I wanted to change those images dynamiclly so: 我想动态地更改这些图像,以便:
I used using (bitmap = new Bitmap...)
and saved a new bitmap picture. 我
using (bitmap = new Bitmap...)
并保存了新的位图图片。
I assign the new bitmap to be on the button. 我将新的位图分配到按钮上。
Then, I tried to delete the old bitmap by calling Dispose()
and then System.IO.File.Delete(nameToDelete)
; 然后,我尝试通过调用
Dispose()
然后删除System.IO.File.Delete(nameToDelete)
删除旧的位图;
The problem: the File.Delete
function throws an exception: "file is being used by another process" and I can't delete it. 问题:
File.Delete
函数引发异常: “文件正在被另一个进程使用” ,我无法删除它。
I also tried calling GC.Collect()
and assigning the bitmap to null
but it didn't work. 我还尝试调用
GC.Collect()
并将位图分配为null
但是它不起作用。
The only "solution" I find is to call Thread.Sleep(2)
before deleting, But it's a patch and doesn't work each time. 我发现的唯一“解决方案”是在删除之前调用
Thread.Sleep(2)
,但这是一个修补程序,并非每次都起作用。
Here is the code (layerPics[z] is an array that holds all the bitmaps, one for each button): 这是代码(layerPics [z]是一个包含所有位图的数组,每个按钮一个):
string name = "new name";
Bitmap bitmap;
using (bitmap = new Bitmap(x, y))
{
Form.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(name);
button.BackgroundImageLayout = ImageLayout.Stretch;
button.BackgroundImage = Image.FromFile(name);
}
layerPics[z].Dispose();
layerPics[z] = null;
layerPics[z] = bitmap;
What can I do? 我能做什么? Thanks!
谢谢!
It's not the Bitmap
that causes the problem, but this line: 导致问题的原因不是
Bitmap
,而是以下行:
Buttons.BackgroundImage = Image.FromFile(name);
Here, you create an instance of an Image
class using the factory method FromFile()
. 在这里,您使用工厂方法
FromFile()
创建Image
类的实例。 The file remains locked until the Image
is disposed. 该文件将保持锁定,直到处理完
Image
为止。
This is the reference . 这是参考 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.