2016-03-08 60 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

谢谢你,创造奇迹! –