What are the methods for downloading files in C#?
There are multiple ways to download files in C#.
- To utilize the WebClient class: You can download files using the DownloadFile method of the WebClient class. Here is an example:
string url = "http://example.com/file.txt";
string savePath = "C:\\Downloads\\file.txt";
using (WebClient client = new WebClient())
{
client.DownloadFile(url, savePath);
}
- Utilizing the HttpClient class: You can use the GetAsync method of the HttpClient class to download a file. Here is an example:
string url = "http://example.com/file.txt";
string savePath = "C:\\Downloads\\file.txt";
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
using (Stream contentStream = await response.Content.ReadAsStreamAsync(),
stream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
await contentStream.CopyToAsync(stream);
}
}
- By using the WebRequest and WebResponse classes: you can send an HTTP request with the WebRequest class, and retrieve response data with the WebResponse class. Here is an example:
string url = "http://example.com/file.txt";
string savePath = "C:\\Downloads\\file.txt";
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream(),
stream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
The above are three commonly used methods for downloading files, you can choose the method that suits your needs.