本章讲述:如何在C#中使用HttpClient直接从阿里云OSS下载文件。
步骤1: 添加必要的命名空间
cs
using System;
using System.IO;
using System.Net.Http;
步骤2: 创建下载方法
以下是使用HttpClient下载文件的示例代码:
cs
public class OssDownloader
{
//downloadPath 是完整的下载地址
public void DownloadFileFromOss(string localFilePath, string downloadPath)
{
using (var client = new HttpClient())
{
try
{
var url = downloadPath;
Console.WriteLine($"Downloading file from: {url}");
// 发送GET请求下载文件
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
byte[] contentBytes = response.Content.ReadAsByteArrayAsync().Result;
File.WriteAllBytes(localFilePath, contentBytes);
Console.WriteLine($"File downloaded successfully to: {localFilePath}");
}
else
{
Console.WriteLine($"Failed to download file. Status code: {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error downloading file: {ex.Message}");
}
}
}
public static void Main(string[] args)
{
OssDownloader downloader = new OssDownloader();
string localFilePath = @"C:\path\to\local\file.txt";
string downloadFilePath = "your download file";//实际的下载地址
downloader.DownloadFileFromOss(localFilePath,downloadFilePath);
}
}
注意事项
确保你的阿里云账号有权限访问指定的Bucket和对象。
处理异常情况,确保资源正确释放。
使用HttpClient时要注意异步编程模型(如使用async/await),以避免阻塞主线程。