【问题标题】:WebClient.DownloadFile path problemsWebClient.DownloadFile 路径问题
【发布时间】:2020-09-24 03:57:19
【问题描述】:

我正在使用 WebClient.DownloadFile 将图像下载到本地存储库,如下所示:

            WebClient myWC = new WebClient();
            myWC.Credentials = new System.Net.NetworkCredential(username, password);
            string photoPath = @"\images\Employees\" + employee + ".jpg";
            myWC.DownloadFile(userResult[12].Values[0].Value.ToString(), photoPath);

我的预期结果如下:我的网络应用部署在这里:

C:\Inetpub\wwwroot\MyWebApp

我希望这会将照片保存到

C:\Inetpub\wwwroot\MyWebApp\images\Employees...

相反,我所有的照片都保存在这里:

C:\images\Employees

我想我不完全理解 DownloadFile 方法,因为我觉得路径应该是相对于应用程序部署所在的目录。如何更改路径以使其相对于应用?

注意:我不想使用物理路径,因为我有一个开发和 QA 站点,并且我不希望路径在移动时中断。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    在 ASP.NET 应用程序中,您可以使用 Server.MapPath 方法映射到您网站中相对于您网站根目录的物理文件夹(由 ~ 表示):

    string photoPath = Server.MapPath("~/images/Employees/" + employee + ".jpg");
    

    【讨论】:

    • 你可以使用HttpContext.Current.Server.MapPath("")
    【解决方案2】:

    photoPath 中的前导反斜杠使路径成为从根目录开始的绝对路径(在您的示例中为 C:\)。将其设为相对路径,只需删除前导反斜杠即可:

    string photoPath = @"images\Employees\" + employee + ".jpg";
    

    备注: DownloadFile(...) 不会为您创建目录。确保它在那里:

    Directory.CreateDirectory("images\Employees");
    

    【讨论】:

      【解决方案3】:
      string photoPath = @"images\Employees\" + employee + ".jpg";
      

      在powershell中不起作用并给出以下错误:

      At line:1 char:22
      + string photoPath = @"images\Employees\" + employee + ".jpg";
      +                      ~
      No characters are allowed after a here-string header but before the end of the line.
          + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
          + FullyQualifiedErrorId : UnexpectedCharactersAfterHereStringHeader
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-03
        • 2017-10-02
        • 2012-02-17
        • 2011-12-27
        • 2019-12-14
        • 1970-01-01
        相关资源
        最近更新 更多