无法删除其他进程使用的文件 [英] Cannot delete file used by some other process

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

问题描述

我正在使用以下代码在我的 wpf 应用程序中显示一些图像:

I am displaying some image in my wpf app using following code:

 <Image Source="{Binding Path=TemplateImagePath, Mode=TwoWay}"  Grid.Row="3" Grid.Column="2"  Width="400" Height="200"/>

并通过浏览某个目录在代码背后的构造函数中设置它的绑定属性,以下是代码:

and setting it's binding property inside code behind's constructor by navigating through some directory, below is the code:

DirectoryInfo Dir = new DirectoryInfo(@"D:/Template");
            if (Dir.Exists)
            {
                if (Dir.GetFiles().Count() > 0)
                {
                    foreach (FileInfo item in Dir.GetFiles())
                    {
                        TemplateImagePath = item.FullName;
                    }
                }
            }

但是如果用户上传了一些其他图像,那么我需要删除这个旧图像,我正在通过以下方式将图像绑定设置为空:

but if user upload some other image then I need to delete this old image which is I am doing in the following way and setting image binding to null:

DirectoryInfo Dir = new DirectoryInfo(@"D:/Template");
                if (Dir.Exists)
                {
                    if (Dir.GetFiles().Count() > 0)
                    {
                        foreach (FileInfo item in Dir.GetFiles())
                        {
                            TemplateImagePath= null;
                            File.Delete(item.FullName);
                        }
                    }
                }

但是我收到了无法删除其他进程使用的文件的异常.我怎样才能删除它?

But Iam getting exception that Cannot delete file used by some other process. How can I delete it?

推荐答案

为了能够删除显示在 ImageControl 中的图像,您必须创建一个新的 BitmapImageBitmapFrame 对象具有 BitmapCacheOption.OnLoad 设置.然后会立即从文件中加载位图,之后不会锁定文件.

In order to be able to delete the image while it is displayed in an ImageControl, you have to create a new BitmapImage or BitmapFrame object that has BitmapCacheOption.OnLoad set. The bitmap will then be loaded from file immediately and the file is not locked afterwards.

将您的属性从 string TemplateImagePath 更改为 ImageSource TemplateImage 并像这样绑定:

Change your property from string TemplateImagePath to ImageSource TemplateImage and bind like this:

<Image Source="{Binding TemplateImage}"/>

像这样设置TemplateImage属性:

BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(item.FullName);
image.EndInit();
TemplateImage = image;

或者这个:

TemplateImage = BitmapFrame.Create(
    new Uri(item.FullName),
    BitmapCreateOptions.None,
    BitmapCacheOption.OnLoad);

<小时>

如果您想继续绑定到您的 TemplateImagePath 属性,您可以改为使用 绑定转换器 将字符串转换为 ImageSource,如上所示.


If you want to keep binding to your TemplateImagePath property you may instead use a binding converter that converts the string to an ImageSource as shown above.

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

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