繁体   English   中英

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

[英]C# Downloading Image with same name as in URL

我有一种方法可以从请求的网站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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM