2012-01-18 46 views
3

我試圖從URL下載圖像。該URL有一個安全密鑰追加到最後,我不斷收到以下錯誤: System.Net.WebException:WebClient請求期間發生異常。 ---> System.ArgumentException:路徑中的非法字符ASP.NET下載來自帶查詢字符串的URL的圖像文件

我不確定使用此語法的正確語法。以下是我的代碼如下。

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'做什麼,你認爲它。 – 2012-01-18 19:37:42

+0

它返回指定的路徑字符串的文件名和擴展名 啊,我甚至沒有在那裏看。我需要拆分文件,以便它不抓取本地文件路徑中的查詢字符串。 – user204588 2012-01-18 19:39:32

+0

Brian,就是這樣。男人,當你錯過如此明顯的東西時,我會遇到。你想把你的答案,我會標記它? – user204588 2012-01-18 19:45:04

回答

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; 
+0

真棒解答.. – 2015-01-20 12:41:25