c# .net code爬虫保存互联网图片和文件

调用

 DownFile.DownloadFileAsync("http://sss.quancc.com//Uploads/document/20250508/1f68deba28744364ac76bc93fd97a078.jpg", "D:\\360Downloads\\1.jpg");
  • 注意:得保证有D:\\360Downloads目录;如果你想更灵活看“自动创建目录”

自动创建目录

#region 保存文件 

string url = "http://cmsapi.quanxi.cc//Uploads/document/20250508/1f68deba28744364ac76bc93fd97a078.jpg"; // 你的URL
string fileName = "downloaded_image.png"; // 你想保存的文件名
string specificFolder = "D:\\360Downloads\\MyImages\\"; // 你想要保存文件的具体子文件夹名称
string savePath = Path.Combine(specificFolder, fileName); // 构建完整保存路径

// 检查并创建目录(如果不存在)
string directoryPath = Path.GetDirectoryName(savePath);
if (!Directory.Exists(directoryPath))
{
	Directory.CreateDirectory(directoryPath);
	Console.WriteLine($"已创建目录: {directoryPath}");
}

DownFile.DownloadFileAsync("http://cmsapi.quanxi.cc//Uploads/document/20250508/1f68deba28744364ac76bc93fd97a078.jpg", specificFolder+ fileName);
#endregion

核心方法

    public class DownFile
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">文件原始路径 如:http://www.baidu.com/1.png</param>
        /// <param name="savePath">文件保存路径“如:D:\\ceshi\\1.png”</param>
        /// <returns></returns>
        public static async Task DownloadFileAsync(string url, string savePath)
        {
            using HttpClient client = new HttpClient();

            try
            {
                // 发送GET请求获取文件流
                HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                response.EnsureSuccessStatusCode(); // 确保请求成功

                // 将响应内容保存到本地文件
                using var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None);
                await response.Content.CopyToAsync(fs);

                Console.WriteLine($"文件已成功下载并保存为 {savePath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"下载文件时出错: {ex.Message}");
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橙-极纪元JJYCheng

客官,1分钱也是爱,给个赏钱吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值