调用
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";
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
{
public static async Task DownloadFileAsync(string url, string savePath)
{
using HttpClient client = new HttpClient();
try
{
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}");
}
}
}