2016-03-08 64 views
1

我有一種方法來保存所請求的網站URL的圖像,但它將圖像保存爲wallpaper.jpg。 ?有沒有一種方法可行使用相同的名稱保存圖像在指定網址(例如https://i.imgur.com/l7s8uDA.png作爲l7s8uDA.jpgC#下載具有相同名稱的圖像在URL中

下面的代碼:

private void DownloadImage(string uri) 
{ 
    string fileName = Environment.CurrentDirectory + "\\Wallpapers\\wallpaper.jpg"; 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

    // Check that the remote file was found. The ContentType 
    // check is performed since a request for a non-existent 
    // image file might be redirected to a 404-page, which would 
    // yield the StatusCode "OK", even though the image was not 
    // found. 
    if ((response.StatusCode == HttpStatusCode.OK || 
     response.StatusCode == HttpStatusCode.Moved || 
     response.StatusCode == HttpStatusCode.Redirect) && 
     response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase)) 
    { 
     // if the remote file was found, download oit 
     using (Stream inputStream = response.GetResponseStream()) 
     using (Stream outputStream = File.OpenWrite(fileName)) 
     { 
      byte[] buffer = new byte[4096]; 
      int bytesRead; 

      do 
      { 
       bytesRead = inputStream.Read(buffer, 0, buffer.Length); 
       outputStream.Write(buffer, 0, bytesRead); 
      } while (bytesRead != 0); 
     } 
    } 
} 
+1

你是捷威將文件名稱作爲wallpaper.jpg,然後顯然它將被保存爲wallpaper.jpg。 – VVN

+0

試試'string fileName = Environment.CurrentDirectory +「\\ Wallpapers \\」+ uri.ToString()+「.jpg」;'? – coderblogger

+0

@ avantvous,使用這個文件名將是完整的uri字符串。 – VVN

回答

3

你可以從URI的文件名是這樣的:

var uri = new Uri("https://i.imgur.com/l7s8uDA.png"); 
var name= System.IO.Path.GetFileName(uri.LocalPath); 

此外,如果您需要在不擴展文件名:

var name = System.IO.Path.GetFileNameWithoutExtension(uri.LocalPath) 
+1

謝謝你,創造奇蹟! –

相關問題