C#怎么实现文件下载功能
作者:野牛程序员:2023-12-25 12:02:44C#阅读 2650
使用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
