我有一种方法可以从请求的网站网址中保存图片,但会将图片另存为wallpaper.jpg
。是否可以保存与给定url中的名称相同的图像(例如,将https://i.imgur.com/l7s8uDA.png作为l7s8uDA.jpg
?
这是代码:
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);
}
}
}
您可以通过以下方式从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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句