我尝试使用Image源时出现ObjectDisposedException

时间:2013-11-03 16:26:58

标签: c# wpf image exception stream

我需要在面板中添加Image,因此我使用以下代码:

var image = new Image();
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;
source.StreamSource = new FileStream(filename, FileMode.Open);
source.EndInit();

// I close the StreamSource so I can load again the same file
source.StreamSource.Close();
image.Source = source;

问题在于,当我尝试使用我的图像源时,我得到ObjectDisposedException

var source = ((BitmapImage)image.Source).StreamSource;

// When I use source I get the exception
using (var stream = new MemoryStream((int)(source.Length)))
{
    source.Position = 0;
    source.CopyTo(stream);
    // ...
}

这是因为我关闭了源代码,但如果我不关闭它,我就无法再次加载相同的文件。

如何解决此问题(即关闭源以便能够多次加载同一个文件,并且能够在不获取异常的情况下使用源)?

1 个答案:

答案 0 :(得分:3)

以下解决方案适合您:

var image = new Image();
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;

// Create a new stream without disposing it!
source.StreamSource = new MemoryStream();

using (var filestream = new FileStream(filename, FileMode.Open))
{
   // Copy the file stream and set the position to 0
   // or you will get a FileFormatException
   filestream.CopyTo(source.StreamSource);
   source.StreamSource.Position = 0;
}

source.EndInit();
image.Source = source;