我正在为Microsoft PixelSense编写应用程序,我正在使用WPF来开发用户界面。
该应用需要从互联网上下载一些内容。应该能够应对互联网连接在下载时突然中断的情况。因此,当我需要一个互联网连接时,我得到一个try catch并捕获因互联网中断而导致的每个WebException或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
。
答案 0 :(得分:1)
您所述的问题是,失败的网络提取最终可能会破坏您要使用的备份资源。
正如下面的评论中所讨论的,这是由于在写入磁盘期间从网络中提取图像流时抛出异常。使用这种代码应该可以保护您免受此类攻击。不用说,您应该对正在返回的流的长度执行一些健全性检查。
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);