在C#中下載文件有多種方法:
string url = "http://example.com/file.txt";
string savePath = "C:\\Downloads\\file.txt";
using (WebClient client = new WebClient())
{
client.DownloadFile(url, savePath);
}
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);
}
}
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);
}
}
以上是三種常用的下載文件的方法,你可以根據自己的需求選擇適合的方法。