You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中用Curl从Artifactory下载文件:进度查看及优化方案咨询

Artifactory ZIP文件下载的优化方案与进度监控

一、通过Curl实现下载进度监控

你当前的代码无法获取下载进度,核心原因有两个:

  1. Curl的进度信息默认输出到标准错误流(stderr),而非你重定向的标准输出(stdout)
  2. 非终端环境下Curl默认不输出进度,需要显式添加参数启用

修改后的Curl调用代码

using System.Diagnostics;
using System.Text;

var process = new Process()
{
    StartInfo = new ProcessStartInfo()
    {
        FileName = "curl",
        // 添加--progress-bar启用进度输出,保留原有认证与下载参数
        Arguments = $"-H \"X-JFrog-Art-Api:<Token>\" -X GET \"{url}\" -O \"{path}\" --progress-bar",
        UseShellExecute = false,
        CreateNoWindow = true,
        RedirectStandardError = true, // 重定向错误流以捕获进度
        StandardErrorEncoding = Encoding.UTF8
    }
};

// 异步读取错误流解析进度
process.ErrorDataReceived += (sender, e) =>
{
    if (!string.IsNullOrEmpty(e.Data))
    {
        // Curl进度行格式为多组数字,可根据需求解析已下载/总字节数,此处直接输出进度文本
        Console.WriteLine($"下载进度:{e.Data}");
    }
};

process.Start();
process.BeginErrorReadLine(); // 启动异步错误流读取
process.WaitForExit();

注意:这种方式依赖系统已安装Curl,且进度输出格式可能因环境略有差异,解析逻辑需要适配。

二、更优方案:使用.NET原生HttpClient实现

直接使用.NET内置的HttpClient是更可靠的选择,无需依赖外部工具,原生支持精准进度监控,代码更易维护和集成。

实现代码(带进度回调)

using System.Net.Http.Headers;
using System.IO;

public async Task DownloadArtifactoryZipAsync(string url, string token, string savePath, IProgress<int>? progress = null)
{
    using var httpClient = new HttpClient();
    // 添加Artifactory认证头
    httpClient.DefaultRequestHeaders.Add("X-JFrog-Art-Api", token);

    // 先获取响应头,避免一次性加载整个文件到内存
    using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
    response.EnsureSuccessStatusCode(); // 确保请求返回成功状态

    var totalBytes = response.Content.Headers.ContentLength ?? -1;
    var downloadedBytes = 0L;

    using var stream = await response.Content.ReadAsStreamAsync();
    using var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None);

    var buffer = new byte[8192];
    int bytesRead;
    while ((bytesRead = await stream.ReadAsync(buffer)) > 0)
    {
        await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead));
        downloadedBytes += bytesRead;

        // 计算并报告进度(仅当总字节数可获取时)
        if (totalBytes > 0 && progress != null)
        {
            var progressPercentage = (int)((downloadedBytes * 100) / totalBytes);
            progress.Report(progressPercentage);
        }
    }
}

// 调用示例
await DownloadArtifactoryZipAsync(
    url: "你的Artifactory文件URL",
    token: "你的API Token",
    savePath: @"C:\downloads\target.zip",
    progress: new Progress<int>(percent =>
    {
        Console.WriteLine($"下载进度:{percent}%");
    })
);

该方案的核心优势

  • 跨平台兼容:无需依赖外部工具,Windows、Linux、macOS均原生支持
  • 进度精准:直接基于字节流计算进度,无格式解析成本
  • 性能更优:支持异步操作,不会阻塞主线程,且采用流式下载避免内存溢出
  • 易于维护:代码完全集成在.NET应用内,调试和扩展更方便

内容的提问来源于stack exchange,提问作者Deto24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 00:20:24