WebClient.下载文件路径问题



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

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

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

C: \Inetpub\wwwroot\MyWebApp

我希望这能将照片保存到

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

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

C: \images\员工

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

注意:我不想使用物理路径,因为我有一个开发和QA网站,如果事情发生变化,我不希望路径中断。

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

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

photoPath中的前导反斜杠使路径成为从根目录开始的绝对路径(示例中为C:(。一定要使它成为一个相对路径,只需删除前导反斜杠:

string photoPath = @"imagesEmployees" + employee + ".jpg";

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

Directory.CreateDirectory("imagesEmployees");
string photoPath = @"imagesEmployees" + employee + ".jpg";

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

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

最新更新