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

3

我正在尝试从URL下载图像。该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
我认为 Path.GetFileName 不是你想象中的那样。 - Brian Driscoll
它返回指定路径字符串的文件名和扩展名。哦,我甚至没有看那里。我需要拆分文件,这样它就不会在本地文件路径中获取查询字符串。 - user204588
布莱恩,就是这样。老兄,我很生气你会错过这么明显的事情。你想把你的答案写下来,然后我来标记它吗? - user204588
我刚刚为您添加了一个答案... - Brian Driscoll
1个回答

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;

在我的情况下,我收到了一个异常,提示“不支持给定路径的格式”。该怎么办? - Rohan Rao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接