在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())
{
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);
}
}
}
}
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();
请注意,以上代码示例中的URL和保存路径应根据实际情况进行更改。另外,下载文件时可能需要处理一些异常情况,例如网络连接失败或文件无法访问等。