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

时间:2016-03-08 10:49:50

标签: c# image download

我有一种方法可以保存来自请求的网站网址的图片,但会将图片保存为wallpaper.jpg。是否有可能使用与给定网址相同的名称保存图片(例如https://i.imgur.com/l7s8uDA.pngl7s8uDA.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);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您可以通过这种方式从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)