C# 根据url 下载文件到指定文件夹下面,url的文件不确定,而且是批量的 ,希望提供可用的代码,实际用过的代码
1条回答 默认 最新
&春风有信 2023-12-15 17:34关注在C#中,你可以使用HttpClient类来下载文件,并使用System.IO命名空间中的类来保存文件到本地。以下是一个示例代码,它根据URL列表下载文件到指定文件夹:
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { // 指定下载文件的URL列表 string[] urlList = { "http://example.com/file1.txt", "http://example.com/file2.txt", "http://example.com/file3.txt" }; // 指定下载文件的保存路径 string targetDirectory = @"C:\path\to\save\files"; foreach (var url in urlList) { // 创建HttpClient实例 using (HttpClient httpClient = new HttpClient()) { try { // 发送GET请求到URL HttpResponseMessage response = await httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); // 确保响应成功 // 读取响应内容作为ByteArrayContent byte[] content = await response.Content.ReadAsByteArrayAsync(); // 创建本地文件路径和名称 string localFilePath = Path.Combine(targetDirectory, Path.GetFileName(new Uri(url))); // 将响应内容写入本地文件 File.WriteAllBytes(localFilePath, content); Console.WriteLine($"Downloaded {Path.GetFileName(localFilePath)} from {url}"); } catch (HttpRequestException e) { Console.WriteLine($"Exception caught for URL {url}: {e.Message}"); } } } } }请确保将urlList变量设置为你想要下载的文件的URL列表,将targetDirectory变量设置为你想要保存文件的文件夹路径。这段代码会循环遍历URL列表,对每个URL发送GET请求,然后将响应内容保存为本地文件。如果下载过程中出现异常,将会在控制台输出错误信息。
评论 打赏 举报解决 1无用