在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);
}
}
以上是三种常用的下载文件的方法,你可以根据自己的需求选择适合的方法。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: c#中typeof的用法是什么