当我尝试使用图像源时c#-ObjectDisposedException
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了当我尝试使用图像源时c#-ObjectDisposedException,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1298字,纯文字阅读大概需要2分钟。
内容图文
我需要将图像添加到面板中,因此我使用以下代码:
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);
// ...
}
发生这种情况是因为我关闭了源,但是如果不关闭源,将无法再次加载相同的文件.
我该如何解决此问题(即关闭源,以便能够多次加载同一文件,并且能够在不获取异常的情况下使用源)?
解决方法:
以下解决方案应为您工作:
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;
内容总结
以上是互联网集市为您收集整理的当我尝试使用图像源时c#-ObjectDisposedException全部内容,希望文章能够帮你解决当我尝试使用图像源时c#-ObjectDisposedException所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。