无法将文件下载到应用程序数据文件夹中
本文关键字:数据 文件夹 应用程序 文件下载 | 更新日期: 2023-09-27 17:57:21
im 尝试编写一些代码来下载文件并将其保存在 AppData 中,但由于某种原因,我在DownloadFile()
调用期间不断收到异常。
例外:
类型为"System.Net.WebException"的未处理异常发生在 系统.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());
}
}
}
您可能会遇到写入该文件夹的权限问题。检查您的进程是否具有 AppData 文件夹的写入权限。如果使用的是 IIS,则必须允许的用户位于窗体IIS AppPool'DefaultAppPool
中,您必须将 DefaultAppPool 替换为应用池名称。