HttpClient 下载文件

private static async Task DownloadFile(string url, string filePath)
{
    var progressMessageHandler = new ProgressMessageHandler(new HttpClientHandler());
    HttpRequestMessage httpRequestMessage = new()
    {
        Method = HttpMethod.Get,
        RequestUri = new Uri(url)
    };
    var httpClient = new HttpClient(progressMessageHandler);

    progressMessageHandler.HttpReceiveProgress += (sender, e) =>
    {
        int num = e.ProgressPercentage;
        if (num != 100)
        {
            Console.Write("\r" + num + " %");
        }
        else
        {
            Console.WriteLine("\r" + num + " %");
        }
    };
    var response = await httpClient.SendAsync(httpRequestMessage);
    using Stream stream = await response.Content.ReadAsStreamAsync();
    using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.Write);
    stream.CopyTo(fileStream);
}

 

static void Main(string[] args)
{
    Random rnd = new Random();
    ConsoleBar cb = new ConsoleBar();
    while (cb.Percent < 1)
    {
          // 使用时只要修改 Percent 这个属性即可自动更新。
        cb.Percent += rnd.NextDouble() * 0.01; 
        Thread.Sleep(10);
    }
}

 

private static async Task DownloadFile(string url, string filePath)
{
    var progressMessageHandler = new ProgressMessageHandler(new HttpClientHandler());
    HttpRequestMessage httpRequestMessage = new()
    {
        Method = HttpMethod.Get,
        RequestUri = new Uri(url)
    };
    var httpClient = new HttpClient(progressMessageHandler);

    ConsoleBar cb = new();
    progressMessageHandler.HttpReceiveProgress += (sender, e) =>
    {
        cb.Percent = e.ProgressPercentage * 0.01;
    };
    var response = await httpClient.SendAsync(httpRequestMessage);
    using Stream stream = await response.Content.ReadAsStreamAsync();
    using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.Write);
    stream.CopyTo(fileStream);
    Console.WriteLine();
}
class ConsoleBar
{
    public int Top { get; set; }
    public int Left { get; set; }

    public int Length { get; set; } = 80;

    double percent = 0;
    public double Percent
    {
        get => percent;
        set
        {
            if (percent == value)
                return;
            percent = value;
            Update();
        }
    }

    public ConsoleColor BackColor { get; set; } = ConsoleColor.Blue;
    public ConsoleColor ForeColor { get; set; } = ConsoleColor.White;

    private static void Show(string s)
    {
        Console.Write(s);
    }

    public ConsoleBar()
    {
        Left = Console.CursorLeft;
        Top = Console.CursorTop;
        Console.SetCursorPosition(Left, Top);
        Console.WriteLine(new string('*', Length));
        for (int i = 0; i < Length; i++)
        {
            Show(" ");
        }
        Console.WriteLine();
        Console.WriteLine(new string('*', Length));
    }

    public ConsoleBar(int left = 0, int top = 0)
    {
        Left = left;
        Top = top;
        Console.SetCursorPosition(Left, Top);
        Console.WriteLine(new string('*', Length));
        for (int i = 0; i < Length; i++)
        {
            Show(" ");
        }
        Console.WriteLine();
        Console.WriteLine(new string('*', Length));
    }

    public void Update()
    {
        Percent = Percent > 1 ? 1 : Percent;
        Percent = Percent < 0 ? 0 : Percent;
        Console.SetCursorPosition(Left, Top + 1);
        ConsoleColor backColor = Console.BackgroundColor;
        ConsoleColor foreColor = Console.ForegroundColor;
        Console.BackgroundColor = BackColor;
        Console.ForegroundColor = ForeColor;
        int max = (int)(Percent * Length);
        for (int i = 0; i < max; i++)
        {
            Show(" ");
        }
        Console.BackgroundColor = backColor;
        Console.ForegroundColor = foreColor;

        int x = Console.CursorLeft;
        int y = Console.CursorTop;
        Console.SetCursorPosition(Left + 35, Top);
        Console.Write(" " + Percent.ToString("P") + " ");
        Console.SetCursorPosition(x, y);
        Console.WriteLine();
    }
}

 下载大文件

private static async Task DownloadFile(string url, string filePath)
{
    var progressMessageHandler = new ProgressMessageHandler(new HttpClientHandler { MaxRequestContentBufferSize = int.MaxValue });
    HttpRequestMessage httpRequestMessage = new()
    {
        Method = HttpMethod.Get,
        RequestUri = new Uri(url)
    };

    var httpClient = new HttpClient(progressMessageHandler);

    ConsoleBar cb = new();
    cb.Update();
    progressMessageHandler.HttpReceiveProgress += (sender, e) =>
    {
        cb.Percent = e.ProgressPercentage * 0.01;
    };
    var response = await httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead);
    response.EnsureSuccessStatusCode();
    using Stream stream = await response.Content.ReadAsStreamAsync();
    using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.Write);
    stream.CopyTo(fileStream);
    Console.WriteLine();
}

 

posted @ 2024-04-04 14:42  邪不压正!  阅读(266)  评论(0编辑  收藏  举报