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

从Azure DevOps流水线下载的Zip文件为空问题求助

问题

尝试从Azure DevOps流水线下载Zip格式的制品,参考相关实现后接近完成,但遇到问题:下载后的Zip文件用Windows资源管理器或其他工具解压时显示为空。已确认制品本身和下载URL有效——断点调试验证URL与Web UI获取的一致,推测是下载或创建Zip文件的代码存在问题,相关代码如下:

static private async Task DownloadArtifactWithHttpClient(string artifactDownloadUrl, string artifactName, string downloadPath)
{
    try
    {
        var localZipFilePath = downloadPath + $"\\{artifactName}.zip";

        // Use HttpClient to download the artifact
        using (var tempClient = new HttpClient())
        {
            // Send request to the DownloadUrl specificed in the BuildArtifact
            HttpResponseMessage response = await tempClient.GetAsync(artifactDownloadUrl);

            if (!response.IsSuccessStatusCode)
            {
                // Something went wrong, shouldn't happen
                throw new Exception($"Error downloading artifact: {response.StatusCode}:{response.ReasonPhrase}");
            }

            // Save the stream to a file
            using (Stream zipFile = File.Create(localZipFilePath))
            {
                await response.Content.CopyToAsync(zipFile);
            }
        }

        // All done!
        Console.WriteLine($"Done downloading too, {localZipFilePath}");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception: " + ex.Message);
        if (ex.InnerException != null) Console.WriteLine("Detailed Info: " + ex.InnerException.Message);
        Console.WriteLine("Stack:\n" + ex.StackTrace);
    }
    
}
解决建议
  • 添加Azure DevOps认证头:Azure DevOps的制品下载URL需要身份验证,直接请求可能返回空白内容(状态码仍为200)。需在HttpClient中添加认证头,比如使用个人访问令牌(PAT):
    var pat = "你的PAT令牌";
    tempClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", 
        Convert.ToBase64String(Encoding.ASCII.GetBytes($":{pat}")));
    
  • 修复路径拼接问题:直接用字符串拼接路径可能导致格式错误,改用Path.Combine确保路径正确:
    var localZipFilePath = Path.Combine(downloadPath, $"{artifactName}.zip");
    
  • 验证下载内容长度:添加日志检查实际下载的字节数,确认是否真的获取到内容:
    if (response.Content.Headers.ContentLength.HasValue)
    {
        Console.WriteLine($"预期下载字节数:{response.Content.Headers.ContentLength.Value}");
    }
    var stream = await response.Content.ReadAsStreamAsync();
    Console.WriteLine($"实际读取字节数:{stream.Length}");
    
  • 确保流正确刷新:在CopyToAsync后手动刷新流,避免数据未完全写入文件:
    await response.Content.CopyToAsync(zipFile);
    await zipFile.FlushAsync();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:41:46