ASP.NET使用查询字符串从URL下载图像文件

时间:2012-01-18 19:31:52

标签: c# asp.net .net

我正在尝试从网址下载图片。 URL有一个附加到结尾的安全密钥,我不断收到以下错误: System.Net.WebException:WebClient请求期间发生异常。 ---> System.ArgumentException:路径中的非法字符

我不确定要使用的正确语法。以下是我的代码。

string remoteImgPath = "https://mysource.com/2012-08-01/Images/front/y/123456789.jpg?api_key=RgTYUSXe7783u45sRR";
string fileName = Path.GetFileName(remoteImgPath);
string localPath = AppDomain.CurrentDomain.BaseDirectory + "LocalFolder\\Images\\Originals\\" + fileName;
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImgPath, localPath);
return localPath;

1 个答案:

答案 0 :(得分:8)

我认为这就是你要找的东西:

string remoteImgPath = "https://mysource.com/2012-08-01/Images/front/y/123456789.jpg?api_key=RgTYUSXe7783u45sRR";
Uri remoteImgPathUri = new Uri(remoteImgPath);
string remoteImgPathWithoutQuery = remoteImgPathUri.GetLeftPart(UriPartial.Path);
string fileName = Path.GetFileName(remoteImgPathWithoutQuery);
string localPath = AppDomain.CurrentDomain.BaseDirectory + "LocalFolder\\Images\\Originals\\" + fileName;
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImgPath, localPath);
return localPath;