gpt4 book ai didi

C# 下载与 URL 中名称相同的图像

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:37 24 4
gpt4 key购买 nike

我有一种方法可以从请求的网站 url 保存图像,但它将图像保存为 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)

关于C# 下载与 URL 中名称相同的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35865353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com