删除另一个进程正在使用的文件 [英] Delete a file being used by another process

查看:30
本文介绍了删除另一个进程正在使用的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式删除一个文件,但该文件显然正被另一个进程(恰好是我的程序)使用.基本上,程序通过使用 FromUri 创建位图从文件夹加载图像,然后将其加载到图像数组中,该数组又成为堆栈面板的子项.效率不高,但很管用.

I'm trying to programmically delete a file, but the file is apparently being used by another process (which happens to be my program). Basically, the program loads images from a folder by using FromUri to create a Bitmap, which is then loaded into an Image array, which in turn becomes the child of a stackpanel. Not very efficient, but it works.

我已尝试清除堆栈面板的子项,并使数组中的图像为空,但我仍然收到 IOException,告诉我该文件正被另一个进程使用.

I've tried clearing the stackpanel's children, and making the images in the array null, but I'm still getting the IOException telling me that the file is being used by another process.

是否有其他方法可以从我的应用程序进程中删除文件?

Is there some other way to remove the file from my application's processes?

推荐答案

为了在加载后释放图像文件,您必须通过设置 BitmapCacheOption.OnLoad 标志来创建图像.一种方法是这样的:

In order to release an image file after loading, you have to create your images by setting the BitmapCacheOption.OnLoad flag. One way to do this would be this:

string filename = ...
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filename);
image.EndInit();

虽然设置 BitmapCacheOption.OnLoad 对从本地文件 Uri 加载的 BitmapImage 起作用,但这是无处记录的.因此,可能更好或更安全的方法是通过设置 StreamSource 属性而不是 UriSource 来从 FileStream 加载图像:

Although setting BitmapCacheOption.OnLoad works on a BitmapImage that is loaded from a local file Uri, this is afaik nowhere documented. Therefore a probably better or safer way is to load the image from a FileStream, by setting the StreamSource property instead of UriSource:

string filename = ...
BitmapImage image = new BitmapImage();

using (var stream = File.OpenRead(filename))
{
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.StreamSource = stream;
    image.EndInit();
}

这篇关于删除另一个进程正在使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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