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

使用C#调用azcopy工具运行失败,求可行实现方案

C# 调用AzCopy失败的修复方案

核心问题说明

  • 原代码调用cmd.exe时未添加/c参数,cmd无法正确执行传入的命令
  • 额外调用cmd属于冗余操作,可直接指向azcopy.exe作为启动进程,减少中间环节出错概率
  • 未捕获标准错误流,无法定位azcopy执行时返回的具体错误信息
  • 若C#项目编译为32位,在64位系统下访问C:\Windows\System32会被自动重定向到C:\Windows\SysWOW64,导致找不到放置的azcopy.exe

可行实现代码

using System;
using System.Diagnostics;
using System.Text;

namespace AzCopyDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 可直接将azcopy.exe放在程序运行目录,用相对路径调用,避免系统路径权限/重定向问题
            string azcopyPath = @"C:\Windows\System32\azcopy.exe";
            // 仅传入azcopy执行参数,不需要带azcopy.exe本身
            string arguments = @"sync ""D:\temp"" ""https://myhubforazcopy.blob.core.windows.net/myhubforazcopy1?sp=racwdl&st=2021-09-05T17:19:11Z&se=2021-09-06T01:19:11Z&spr=https&sv=2020-08-04&sr=c&sig=MAraJ0PxqJMDdYuWzrOUEwYda%2BkXEukP%2Fs%3D"" --destination-delete=true";
       
            CallProcess(azcopyPath, arguments);
        }

        public static void CallProcess(string fileName, string arguments)
        {
            var process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = fileName,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true, // 新增捕获错误流,方便定位问题
                Arguments = arguments,
                UseShellExecute = false,
                CreateNoWindow = true,
                WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory // 自动适配程序运行目录
            };

            process.StartInfo = startInfo;
            // 异步读取流,避免缓冲区满导致进程卡死
            StringBuilder output = new StringBuilder();
            StringBuilder error = new StringBuilder();
            process.OutputDataReceived += (sender, e) => { if (e.Data != null) output.AppendLine(e.Data); };
            process.ErrorDataReceived += (sender, e) => { if (e.Data != null) error.AppendLine(e.Data); };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            process.WaitForExit();
            
            // 输出执行结果
            Console.WriteLine("执行输出:");
            Console.WriteLine(output.ToString());
            if (error.Length > 0)
            {
                Console.WriteLine("执行错误:");
                Console.WriteLine(error.ToString());
            }
            // AzCopy执行成功退出码为0,可通过该值判断执行结果
            Console.WriteLine($"退出码:{process.ExitCode}");
        }
    }
}

额外注意事项

  • 建议将azcopy.exe放在程序运行目录,不需要放到System32,避免权限和系统路径重定向问题
  • 确认SAS令牌在代码运行时未过期,且拥有对应Blob容器的读写、删除权限
  • 项目属性中把目标平台改为x64或者Any CPU(取消优先32位勾选),避免32位程序访问System32路径被重定向

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:36:03