【发布时间】:2015-06-21 23:53:30
【问题描述】:
我正在尝试编写一些代码来下载文件并将其保存在 AppData 中,但由于某种原因,我在 DownloadFile() 调用期间不断收到异常。
例外:
“System.Net.WebException”类型的未处理异常发生在 系统.dll
附加信息:在 WebClient 期间发生异常 请求。
这是我的代码:
string remoteUri = "http://mhost.site11.com/";
string fileName = "SysSpec.zip", myStringWebResource = null;
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
try
{
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, appData + "\\PPA\\" + fileName);
}
catch (WebException er)
{
var result = GetResponceFromWebException(er);
if (result != null)
{
MessageBox.Show(result.ToString());
}
throw;
}
catch (Exception er)
{
MessageBox.Show(er.ToString());
}
}
}
private HttpRequestResponce GetResponceFromWebException(WebException e)
{
HttpRequestResponce result = null;
if (e.Status == WebExceptionStatus.ProtocolError)
{
try
{
using (var stream = e.Response.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var responseString = reader.ReadToEnd();
var responce = ((HttpWebResponse)e.Response);
result = new HttpRequestResponce(responseString, responce.StatusCode);
}
}
}
}
catch (Exception ex)
{
// log exception or do nothing or throw it
}
}
return result;
}
解决方案:
首先将文件下载到我的程序所在的目录,然后移动它。
string remoteUri = "http://mhost.site11.com/";
string fileName = "SysSpec.zip", myStringWebResource = null;
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
// Move the file
string path = fileName;
string path2 = appData + "\\PPA\\" + fileName;
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) { }
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
}
catch (Exception er)
{
Console.WriteLine("The process failed: {0}", er.ToString());
}
}
}
【问题讨论】:
-
你遇到了什么异常?
-
检查 WebException.Status
-
您可以看到从Web异常响应对象stackoverflow.com/questions/30675121/how-to-catch-exception/…获取数据的示例
标签: c#