【问题标题】:WebClient DownloadFile - Access denied or could not find part of the pathWebClient DownloadFile - 访问被拒绝或找不到路径的一部分
【发布时间】:2014-12-18 03:16:54
【问题描述】:

我正在尝试设置一个按钮,以便用户可以下载保存在服务器上的文件。

protected void btnDownloadHtmlFile_Click(object sender, EventArgs e)
{
    string path = @"D:\web\mytestwebsite.com\www\temp\test.html";
    if (!File.Exists(path))
    {
        File.Create(path);
    }

    TextWriter tw = new StreamWriter(path);
    tw.WriteLine("<head></head><body>test</body>");
    tw.Close();

    WebClient webclient = new WebClient();
    webclient.DownloadFile(@"D:\web\mytestwebsite.com\www\temp\test.html", @"C:\web\test.html");
}

这导致Could not find a part of the path 'C:\web\test.html'. 如果我改变了,也一样

 webclient.DownloadFile(new Uri("http://mytestwebsite.com/temp/test.html"), @"C:\web\test.html");

如果我换了

webclient.DownloadFile(@"D:\web\mytestwebsite.com\www\temp\test.html", "test.html");

webclient.DownloadFile(new Uri("http://mytestwebsite.com/temp/test.html"), "test.html");

我无法访问路径“C:\Windows\SysWOW64\inetsrv\test.html”。

最后我去了文件夹 C:\Windows\SysWOW64\inetsrv 授予 NETWORK SERVICE 权限,但它说访问被拒绝。我在服务器上以管理员身份登录。

我阅读了一些关于此的帖子,但似乎没有任何效果,或者我错过了一些东西。

WebcClient.DownloadFile 的正确使用方法是什么?

【问题讨论】:

  • 首先,为什么需要在服务器位置创建文件并再次将其保存到服务器位置?

标签: c# asp.net webclient-download


【解决方案1】:

让我想到了你的问题。当您使用webclient.DownloadFile(new Uri("http://mytestwebsite.com/temp/test.html"), @"C:\web\test.html"); 时,请确保您在C:\ 中有目录web。我的意思是确保你的文件系统中有C:\web。否则会抛出错误。因为它需要目录存在,所以它可以创建新文件。

当您执行webclient.DownloadFile(@"D:\web\mytestwebsite.com\www\temp\test.html", "test.html"); 时,它尝试在当前执行文件范围内创建文件,即C:\Windows\SysWOW64\inetsrv\ 并尝试在那里创建文件,由于访问权限,它无法在那里创建文件。

解决方案,尝试使用以下代码,它应该在D:\web创建文件。

webclient.DownloadFile(new Uri("http://mytestwebsite.com/temp/test.html"), @"D:\web\test.html");

编辑

免责声明你做错了(如果我不清楚要求),DownloadFile 是下载一个 url 到服务器位置,现在有下载本地文件并保存的点再次到本地位置,就像save as 文件到任何其他位置。

编辑

要允许最终用户下载文件,请使用以下代码。

Response.Clear();
Response.ContentType = "text/html";
Response.AddHeader("Content-Disposition", "attachment;filename=a.html"); // replace a.html with your filename
Response.WriteFile(@"D:\webfile\a.html"); //use your file path here.
Response.Flush();
Response.End();

【讨论】:

  • 错误使用 webclient.downloadfile - 它会将文件下载到服务器上的本地文件 - 而不是客户端
  • 但是按照OP的要求,它会解决目的,它会下载到服务器位置,是OP想要的吗?
  • 他们想下载保存在服务器上的文件
  • 如果您查看 OP 的代码,文件正在服务器上创建并再次将其保存到服务器位置,您这样做有什么意义吗?我的意思是他可能需要在实验基础上了解DownloadFile 的用法。
  • @Greg, downloadfile 是将包含 mp3 、视频、html 内容的 URL 下载到您的服务器位置,您做错了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多