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