即時通訊嘗試編寫一些代碼,下載文件並將其保存在AppData中,但由於某種原因,我在DownloadFile()
調用期間不斷收到異常。無法下載文件到AppData文件夾
例外:
類型 'System.Net.WebException' 的未處理的異常發生在 System.dll中
其他信息:一個Web客戶端 請求期間發生異常。
這裏是我的代碼:
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 – cubrr
您可以看到從Web異常響應對象獲取數據的示例http://stackoverflow.com/questions/30675121/how-to-catch-exception/30675651#30675651 –