1
我有一種方法來保存所請求的網站URL的圖像,但它將圖像保存爲wallpaper.jpg
。 ?有沒有一種方法可行使用相同的名稱保存圖像在指定網址(例如https://i.imgur.com/l7s8uDA.png作爲l7s8uDA.jpg
C#下載具有相同名稱的圖像在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);
}
}
}
你是捷威將文件名稱作爲wallpaper.jpg,然後顯然它將被保存爲wallpaper.jpg。 – VVN
試試'string fileName = Environment.CurrentDirectory +「\\ Wallpapers \\」+ uri.ToString()+「.jpg」;'? – coderblogger
@ avantvous,使用這個文件名將是完整的uri字符串。 – VVN