C# HttpClient 获取图片并保存到本机

要使用HttpClient须引用 using System.Net.Http;
:System.Net.dll和System.Net.Http.dll是两个组件,HttpClient是在后者中定义。

class Program
{
    static void Main()
    {
        //图片路径:https://img.infinitynewtab.com/wallpaper/1.jpg
        string imgSourceURL = "https://img.infinitynewtab.com/wallpaper/";
        DownloadImags(imgSourceURL).Wait();
    }
    private static async Task DownloadImags(string url)
    {
        var client = new HttpClient();
        System.IO.FileStream fs;
        int a = 1;
        //文件名:序号+.jpg。可指定范围,以下是获取100.jpg~500.jpg.
        for (int i = 100; i <= 500; i++)
        {
            var uri = new Uri(Uri.EscapeUriString(url+i.ToString()+".jpg"));
            byte[] urlContents = await client.GetByteArrayAsync(uri);
            fs = new System.IO.FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\images\\"+ i.ToString() + ".jpg",System.IO.FileMode.CreateNew);
            fs.Write(urlContents, 0, urlContents.Length);
            Console.WriteLine(a++);
        }
    }
}

你可能感兴趣的:(随笔)