IOException in WPF GUI
本文关键字:GUI WPF in IOException | 更新日期: 2023-09-27 18:01:36
我正在为微软PixelSense编程一个应用程序,我正在使用WPF开发用户界面。
应用程序需要从互联网下载一些内容。它应该能够应付的情况下,当互联网连接突然中断,而下载。因此,当我需要互联网连接时,我得到了一个try catch,并捕获了由于互联网中断而导致的每个webeexception或IOException。
下面是我的代码片段:
System.Drawing.Image tmpimg = null;
Stream stream = null;
HttpWebResponse httpWebReponse = null;
try
{
// dowloading image
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(urlPicturesBig +urlresource);
httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
stream = httpWebReponse.GetResponseStream();
tmpimg = System.Drawing.Image.FromStream(stream);
// saving
tmpimg.Save(@appDirectory + "''resources''" + urlresource);
}
catch (WebException)
{
Debug.WriteLine("WebException");
return -1;
}
catch (IOException)
{
Debug.WriteLine("IOException");
return -1;
}
问题是,当IOException
被处理时,我的GUI崩溃了(按钮列表变成灰色)。所以我试着这样做:
try
{
// dowloading image
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(urlPicturesBig +urlresource);
httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (WebException)
{
Debug.WriteLine("WebException");
return -1;
}
stream = httpWebReponse.GetResponseStream();
tmpimg = System.Drawing.Image.FromStream(stream);
// saving
tmpimg.Save(@appDirectory + "''resources''" + urlresource);
但即使有一个互联网中断,IOException
被处理,程序不读取catch (WebException)
指令。如果我删除try catch块,大多数时候WebException
被处理,有时它是IOException
。
正如您所说的,问题是失败的网络获取可能最终会损坏您想要使用的备份资源。
如下面的评论所述,这是由于在写入磁盘期间从网络获取图像流时抛出的异常。使用这种代码可以防止这种情况。不用说,您应该对返回的流的长度执行一些完整性检查。
var httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(urlPicturesBig + urlresource);
MemoryStream memory= new MemoryStream();
using (var httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
var stream = httpWebReponse.GetResponseStream();
//read the entire stream into memory to ensure any network issues
//are exposed
stream.CopyTo(memory);
}
var tmpimg = System.Drawing.Image.FromStream(memory); {
tmpimg.Save(@appDirectory + "''resources''" + urlresource);