首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#下载与URL中同名的图像

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

Stack Overflow用户
提问于 2016-03-08 10:49:50
回答 1查看 1.1K关注 0票数 1

我有一个方法来保存一个图像从请求的网站网址,但它保存图像为wallpaper.jpg。是否有可能保存与给定url中的名称相同的图像(例如,https://i.imgur.com/l7s8uDA.png作为l7s8uDA.jpg )

下面是代码:

代码语言:javascript
复制
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);
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-08 10:53:18

您可以通过这种方式从uri获取文件名:

代码语言:javascript
复制
var uri = new Uri("https://i.imgur.com/l7s8uDA.png");
var name= System.IO.Path.GetFileName(uri.LocalPath);

此外,如果您需要没有扩展名的文件名:

代码语言:javascript
复制
var name = System.IO.Path.GetFileNameWithoutExtension(uri.LocalPath)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35865353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档