使用.NET Core从互联网下载文件,代码编译通过但运行报错如何解决?
问题根因
- 最核心的错误是
Split('/', 1)的参数使用错误:String.Split的第二个参数代表返回数组的最大长度,传1意味着永远不会分割字符串,最终得到的文件名是完整的URL地址,拼接后的本地路径包含https:等非法字符,直接触发路径不合法异常。 - 硬编码
\作为路径分隔符,跨平台运行会出错。 - 旧版
WebClient默认未启用高版本TLS协议,访问Python官方HTTPS站点可能出现连接失败问题。
修复后的实现代码
using System; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace download_file { class Program { // 全局静态HttpClient实例,避免重复实例化导致的资源浪费 private static readonly HttpClient _httpClient = new HttpClient(); static async Task Main(string[] args) { // 提前启用TLS 1.2、1.3兼容HTTPS站点 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; string zip_url = @"https://www.python.org/ftp/python/3.9.5/python-3.9.5-embed-amd64.zip"; string currentDirectory = Directory.GetCurrentDirectory(); string dlPath = Directory.CreateDirectory(Path.Combine(currentDirectory, "DL")).FullName; // 用Uri类安全获取文件名,避免手动分割字符串出错 Uri uri = new Uri(zip_url); string fileName = Path.GetFileName(uri.LocalPath); string downloadedFilePath = Path.Combine(dlPath, fileName); // 异步下载避免阻塞主线程 await FileDownloadAsync(zip_url, downloadedFilePath); Console.WriteLine("文件下载完成"); } private static async Task FileDownloadAsync(string url, string savePath) { if (string.IsNullOrEmpty(url)) { return; } if (string.IsNullOrEmpty(savePath)) { Uri uri = new Uri(url); string fileName = Path.GetFileName(uri.LocalPath); savePath = Path.Combine(Directory.GetCurrentDirectory(), fileName); } using var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); response.EnsureSuccessStatusCode(); await using var stream = await response.Content.ReadAsStreamAsync(); await using var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None); await stream.CopyToAsync(fileStream); } } }
额外注意事项
- 如果仍要使用
WebClient实现,只需要把Split的第二个参数删掉,改成zip_url.Split('/')即可解决路径非法问题,但仍建议更换为HttpClient。 - 运行程序时确保当前目录有写入权限,避免权限不足导致的保存失败。
内容的提问来源于stack exchange,提问作者zooid
相关产品推荐
相关产品推荐

