C# 根据url 下载文件到指定文件夹下面,url的文件不确定,而且是批量的 ,希望提供可用的代码,实际用过的代码
1条回答 默认 最新
- Bony- 2023-12-15 17:17关注
以下回答参考GPT并且由Bony-整理:
在C#中,你可以使用WebClient
类来下载文件。以下是一个简单的示例代码,演示如何根据给定的URL下载文件到指定文件夹:using System; using System.Net; class Program { static void Main() { // 指定下载文件的URL和目标文件夹 string[] urls = { "https://example.com/file1.txt", "https://example.com/file2.jpg" }; string destinationFolder = @"C:\Your\Destination\Folder\"; using (WebClient client = new WebClient()) { // 遍历每个URL并下载文件 foreach (string url in urls) { try { // 从URL中获取文件名 string fileName = GetFileNameFromUrl(url); // 构建目标文件的完整路径 string destinationPath = System.IO.Path.Combine(destinationFolder, fileName); // 下载文件 client.DownloadFile(url, destinationPath); Console.WriteLine($"File downloaded: {destinationPath}"); } catch (Exception ex) { Console.WriteLine($"Error downloading file from {url}: {ex.Message}"); } } } Console.ReadLine(); } // 从URL中获取文件名 static string GetFileNameFromUrl(string url) { Uri uri = new Uri(url); return System.IO.Path.GetFileName(uri.LocalPath); } }
请确保替换
urls
数组中的URL为实际的文件URL,以及将destinationFolder
替换为你想要保存文件的目标文件夹路径。此代码使用WebClient
类进行文件下载,并处理了可能的异常情况。本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 孟德尔随机化结果不一致
- ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
- ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
- ¥15 谁有desed数据集呀
- ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
- ¥15 关于#hadoop#的问题
- ¥15 (标签-Python|关键词-socket)
- ¥15 keil里为什么main.c定义的函数在it.c调用不了
- ¥50 切换TabTip键盘的输入法
- ¥15 可否在不同线程中调用封装数据库操作的类