C#怎么实现文件下载功能
作者:野牛程序员:2023-12-25 12:02:44C#阅读 2678
使用C#实现文件下载功能可以通过WebClient类或HttpClient类来实现。以下是使用WebClient类的简单示例:
using System;
using System.Net;
class Program
{
static void Main()
{
string url = "https://example.com/path/to/file.txt";
string destinationPath = "C:\\\\Downloads\\\\file.txt";
using (WebClient client = new WebClient())
{
client.DownloadFile(url, destinationPath);
Console.WriteLine("文件下载完成");
}
}
}上述代码中,需要替换url和destinationPath变量为实际的文件下载链接和保存路径。这个例子使用WebClient的DownloadFile方法,它会将远程文件下载到本地。
如果使用的是.NET Core 或 .NET 5+,也可以使用HttpClient类来实现文件下载:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string url = "https://example.com/path/to/file.txt";
string destinationPath = "C:\\\\Downloads\\\\file.txt";
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
using (HttpContent content = response.Content)
{
byte[] data = await content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes(destinationPath, data);
Console.WriteLine("文件下载完成");
}
}
}
}同样,需要替换url和destinationPath变量。这个例子使用了HttpClient来发送HTTP请求并将文件内容保存到本地文件。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

