问题描述
我想programmically删除一个文件,但该文件显然正在被另一个进程使用(这恰好是我的程序)。基本上,该方案通过使用FromUri来创建位图,然后将其装入一个图像阵列,这反过来又成为一个的StackPanel的子加载从文件夹的图像。不是很有效,但它的作品。
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.
我已经试过清除StackPanel中的孩子,并在阵列空使得图像,但我仍然得到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 $ C $创建你的图片C>标记。这样做的一个方法是这样的:
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的作品,这是AFAIK无处记录。因此,一个可能更好或更安全的方法是从一个FileStream,通过设置的StreamSource
属性,而不是 UriSource
加载图像
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 =
new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}
这篇关于删除文件正被另一个进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!