HttpClient 下載檔案

邪不压正!發表於2024-04-04
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);
}

相關文章