Different ways to download files using C#.

In C#, there are several ways to download files. Here are a few common methods.

  1. Utilize the WebClient class.
string url = "http://example.com/file.txt";
string savePath = "C:\\downloads\\file.txt";

using (WebClient client = new WebClient())
{
    client.DownloadFile(url, savePath);
}
  1. Use the HttpClient class:
string url = "http://example.com/file.txt";
string savePath = "C:\\downloads\\file.txt";

using (HttpClient client = new HttpClient())
{
    using (HttpResponseMessage response = await client.GetAsync(url))
    {
        using (Stream stream = await response.Content.ReadAsStreamAsync())
        {
            using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
            {
                await stream.CopyToAsync(fileStream);
            }
        }
    }
}
  1. Use the WebRequest and WebResponse classes.
string url = "http://example.com/file.txt";
string savePath = "C:\\downloads\\file.txt";

WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();

using (Stream stream = response.GetResponseStream())
{
    using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
    {
        stream.CopyTo(fileStream);
    }
}

response.Close();

Please note that the URL and save path in the code example above should be modified according to the actual situation. Additionally, exceptions such as network connection failure or file access issues may need to be handled when downloading the file.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds