【问题标题】:Delete File during closing Window [duplicate]关闭窗口期间删除文件[重复]
【发布时间】:2014-09-24 13:32:18
【问题描述】:

我认为我的问题与封闭主题有关:How can I stop <Image Source="file path"/> process?。该主题已关闭,它的答案对我不起作用。

我的问题是,我不能使用 File.Delete(path)。它提供异常:“附加信息:该进程无法访问文件 'C:\Images\2014_09\auto_12_53_55_beszelri_modified.jpg',因为它正被另一个进程使用”。

我正在尝试在 Window_OnClosed 事件中调用此方法。这个想法是我必须在关闭窗口时删除图像的 jpg 文件。该文件的路径是 WPF 中图像控件的来源。在调用该方法之前,我尝试将 Image source 设置为 null,但它不起作用。如何在关闭窗口之后或期间删除该文件。当我尝试关闭该位置的其他文件时,它成功了。

这是关闭事件的代码。 CreateFileString 方法创建路径。

private void ImageWindow_OnClosed(object sender, EventArgs e)
{
    var c = CarImage.Source.ToString();
    var a = CreateFileString(c);
    CarImage.Source = null;

    File.Delete(a);
}

【问题讨论】:

  • Image 是否已显示在 UI 中?
  • 我在 XAML 中创建图像。我在 OnLoaded 事件中设置它的来源。图像显示在窗口中,我可以对其进行操作(绘制一些形状)。
  • 检查这些answers
  • 好的,我正在为你添加答案。
  • @user3419073 - 你也可以参考这个 - stackoverflow.com/questions/1688545/….

标签: c# wpf file-io image-file


【解决方案1】:

由于某些烦人的原因,WPF 中的标记解析器会打开图像并保持与物理文件的连接处于打开状态。我在允许用户切换图像时遇到了类似的问题。我解决它的方法是使用IValueConverter 加载Image 并将BitmapImage.CacheOption 设置为BitmapCacheOption.OnLoad。试试这个:

public class FilePathToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value.GetType() != typeof(string) || targetType != typeof(ImageSource)) return false;
        string filePath = value as string;
        if (filePath.IsNullOrEmpty() || !File.Exists(filePath)) return DependencyProperty.UnsetValue;
        BitmapImage image = new BitmapImage();
        try
        {
            using (FileStream stream = File.OpenRead(filePath))
            {
                image.BeginInit();
                image.StreamSource = stream;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.EndInit();
            }
        }
        catch { return DependencyProperty.UnsetValue; }
        return image;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DependencyProperty.UnsetValue;
    }
}

你可以这样使用它:

<Application.Resources>
    <Converters:FilePathToImageConverter x:Key="FilePathToImageConverter" />
</Application.Resources>

...

<Image Source="{Binding SomeObject.SomeImageFilePath, 
    Converter={StaticResource FilePathToImageConverter}, Mode=OneWay}" />

【讨论】:

    猜你喜欢
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2016-01-22
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多