【问题标题】:WPF Cannot delete image from code. IOException [duplicate]WPF 无法从代码中删除图像。 IOException [重复]
【发布时间】:2015-10-08 13:23:02
【问题描述】:

我可能已经阅读了所有关于此的帖子。似乎找不到问题。 这是我的收藏

private ObservableCollection<BitmapImage> _imageList = new ObservableCollection<BitmapImage>();

这就是我加载图像的方式

foreach (string filepath in temp) //populate image collection 
{
    BitmapImage tempImg = new BitmapImage();
    tempImg.BeginInit();
    tempImg.CacheOption = BitmapCacheOption.OnLoad;
    tempImg.UriSource = new Uri(filepath);
    tempImg.EndInit();
    _imageList.Add(tempImg); 
}

当我尝试删除时发生异常,文件正在使用中。

if (File.Exists(_imageList[SelectedItem].UriSource.AbsolutePath.ToString()))
{
    int temp = SelectedItem;
    //_imageList.RemoveAt(temp);
    Console.WriteLine(_imageList[temp].UriSource.AbsolutePath.ToString());
    File.Delete(_imageList[temp].UriSource.AbsolutePath.ToString());
}

例外:

“System.IO.IOException”类型的异常发生在 mscorlib.dll 中,但未在用户代码中处理。

附加信息:该进程无法访问文件“e:\pix\img.jpg”,因为它正被另一个进程使用。

有人可以重新打开它吗?我发现了问题,不是这段代码,是在视图部分,我想发布一个答案。

【问题讨论】:

  • 它可能无法解决您的问题,但您应该添加 tempImg.Freeze();紧接着 tempImg.EndInit();以避免内存泄漏。
  • 谢谢,我已经这样做了,对io异常没有帮助

标签: c# wpf image ioexception


【解决方案1】:

您从列表中删除第 temp 项,然后立即重新使用它。鉴于列表中有足够的项目,错误的文件将被删除。否则你会得到一个 IndexOutOfRangeException。

此外,UriSource.AbsolutePath 是一个字符串,那么使用 ToString() 是没有意义的。

从发布的代码中看不到,为什么该文件可能正在使用中。请检查其他应用程序是否保持文件打开(或您,其他地方)。

【讨论】:

  • 确实如此,但即使没有那段代码,我仍然会得到相同的错误,即 IO 异常。我将再次对其进行编辑以澄清
  • 没有其他应用程序使用该文件,只要我关闭应用程序,我就可以将其从 win 中删除。资源管理器,在关闭之前,它也会给我一个文件正在使用错误。
  • 您的代码中是否还有其他部分可以访问这些文件?
  • 我确实有一个绑定到视图的公共 ObservableCollection ImageList,但我认为它与加载到集合中的文件没有任何关系。
  • 这个其他的ImageList是怎么填的?
【解决方案2】:

但是异常说明了什么?它在哪一行代码被触发? 我敢打赌你的 BitmapImage 保存了文件,这就是为什么你不能删除它,你应该首先处理它。

有时 WPF 只保存文件,在这种情况下,最好只存储文件中的字节并不管它,例如:

  private BitmapImage loadImage(string imgPath)
    {
        BitmapImage myRetVal = null;
        if (imgPath != null)
        {
            BitmapImage img = new BitmapImage();
            using (FileStream stream = File.OpenRead(imgPath))
            {
                img.BeginInit();
                img.CacheOption = BitmapCacheOption.OnLoad;
                img.StreamSource = stream;
                img.EndInit();
            }
            myRetVal = image;
        }
        return myRetVal;
    }

【讨论】:

  • 检查上述替代方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 2011-10-02
  • 2011-04-12
相关资源
最近更新 更多