[英]WebClient.DownloadFile path problems
I am using WebClient.DownloadFile to download an image to a local repository as follows:我正在使用 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);
My expected results were as follows: My web app is deployed here:我的预期结果如下: 我的网络应用程序部署在这里:
C:\\Inetpub\\wwwroot\\MyWebApp
C:\\Inetpub\\wwwroot\\MyWebApp
I expected this to save the photo to我希望这会将照片保存到
C:\\Inetpub\\wwwroot\\MyWebApp\\images\\Employees...
C:\\Inetpub\\wwwroot\\MyWebApp\\images\\Employees...
Instead, all my photos get saved here:相反,我所有的照片都保存在这里:
C:\\images\\Employees
C:\\图像\\员工
I guess I don't completely understand the DownloadFile
method because I felt like the path should be relative to the directory the app is deployed in. How can I change the path so that it is relative to the directory of the app?我想我并不完全理解
DownloadFile
方法,因为我觉得路径应该是相对于应用程序部署所在的目录的。如何更改路径以使其相对于应用程序的目录?
Note: I don't want to use a physical path because I have a Dev and QA site and I don't want the paths to break if things get moved around.注意:我不想使用物理路径,因为我有一个开发和 QA 站点,我不希望路径在移动时中断。
在 ASP.NET 应用程序中,您可以使用Server.MapPath
方法映射到网站内相对于站点根目录(由~
表示)的物理文件夹:
string photoPath = Server.MapPath("~/images/Employees/" + employee + ".jpg");
The leading backslash in your photoPath
makes the path an absolute path starting at the root directory ( C:\\
in your example). photoPath
的前导反斜杠使路径成为从根目录(在您的示例中为C:\\
)开始的绝对路径。 Do make it a relative path just remove the leading backslash:做一个相对路径只需删除前导反斜杠:
string photoPath = @"images\Employees\" + employee + ".jpg";
Remark: DownloadFile(...)
will not create the directory for you.备注:
DownloadFile(...)
不会为您创建目录。 Make sure it's there:确保它在那里:
Directory.CreateDirectory("images\Employees");
string photoPath = @"images\Employees\" + employee + ".jpg";
doesn't work in powershell and gives the following error:在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.