在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和保存路徑應根據實際情況進行更改。另外,下載文件時可能需要處理一些異常情況,例如網絡連接失敗或文件無法訪問等。