相关疑难解决方法(0)

如何在WPF中从图像源中释放图像

我正在加载图像如下

XAML

<Image Stretch="None" Grid.Row="16" Height="70" HorizontalAlignment="Left" Name="imgThumbnail" VerticalAlignment="Top" Width="70" Grid.RowSpan="3" Margin="133,1,0,0" Grid.Column="2" Grid.ColumnSpan="2" />
Run Code Online (Sandbox Code Playgroud)

代码隐藏

if (Path.GetFileNameWithoutExtension(filePath).ToLower().Contains(slugName.ToLower() + "_70x70"))
{
    imgThumbnail.BeginInit();
    imgThumbnail.Stretch = Stretch.UniformToFill;
    imgThumbnail.Source = new BitmapImage(new Uri(filePath));
    imgThumbnail.EndInit();
    count = count + 1;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常,现在我的缩略图旁边有一个删除按钮,如果删除按钮,我想删除源位置的所有图像.

这是删除图像文件的代码

internal int Remove(string slugName, DirectoryInfo outputFolder)
{
    Helper.MetadataView.imgThumbnail.Source = null;

    foreach (string filePath_ToBeDeleted in filePathList_ToBeDeleted)
    {
        if (File.Exists(filePath_ToBeDeleted))
        {
            Helper.MetadataView.imgThumbnail.IsEnabled = false;
            File.Delete(filePath_ToBeDeleted);
            count += 1;
            }
        }
        return count;
    }
    return 0; // slugName == null
}
Run Code Online (Sandbox Code Playgroud)

我试图将源为null并删除,但它会抛出异常,如下所示

该进程无法访问文件'\ serv1\Dev\Images\730_Test4_0406_70x70.jpg',因为它正由另一个进程使用. …

c# wpf image

13
推荐指数
2
解决办法
2万
查看次数

无法删除某些其他进程使用的文件

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

 <Image Source="{Binding Path=TemplateImagePath, Mode=TwoWay}"  Grid.Row="3" Grid.Column="2"  Width="400" Height="200"/>
Run Code Online (Sandbox Code Playgroud)

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

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

但是如果用户上传了一些其他图像,那么我需要删除这个旧图像,这是我按照以下方式进行并将图像绑定设置为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);
                        }
                    }
                }
Run Code Online (Sandbox Code Playgroud)

但我得到的异常是无法删除某些其他进程使用的文件.我该如何删除它?

wpf file-io ioexception c#-4.0

2
推荐指数
1
解决办法
2865
查看次数

标签 统计

wpf ×2

c# ×1

c#-4.0 ×1

file-io ×1

image ×1

ioexception ×1