Search code examples
c#cmdazure-blob-storageazcopy

Unable to run azcopy tool with c#


I have written a console application to call the AZcopy tool programmatically, but I was not able to call azcopy tool. Can you please redirect me the workable source ? I have downloaded azcopy_windows_amd64_10.12.1 and put azcopy.exe into C:\Windows\System32\azcopy.exe location

static void Main(string[] args)
    {
        string strCmdText = @"AzCopy.exe 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(strCmdText);
    }

public static void CallProcess(string strCmdText)
    {
       
        //C:\Windows\System32\azcopy.exe
        var process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = @"C:\Windows\System32\cmd.exe",
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            Arguments = strCmdText,
            UseShellExecute = false,
            CreateNoWindow = false,
            WorkingDirectory = @"D:\AzCopy\bin\Debug\"
        };


        process.StartInfo = startInfo;

        process.Start();

        process.StandardInput.Flush();
        process.StandardInput.Close();
        process.WaitForExit();
        Console.WriteLine(process.StandardOutput.ReadToEnd());
    }

Solution

  • Starting cmd with the program you want to execute as the argument doesn't actually runt that program, you'll need to pass the entire argument (your program) after the /c flag, like so:

    string strCmdText = @"/c AzCopy.exe sync ""D:\temp"" ...
    

    Make sure that AzCopy is in your PATH or specify the precise path to it

    But it would be better if you just directly run AzCopy instead of starting a command prompt which then starts AzCopy, this would be done like so:

    // Notice how the 'azcopy' at the start is gone
    var arguments = @"""D:\temp"" ""https://myhubforazcopy.blob ..."
    
    var process = new Process();
    ProcessStartInfo startInfo = new ProcessStartInfo
    {
        FileName = @"C:\Windows\System32\azcopy.exe",
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        Arguments = arguments,
        UseShellExecute = false,
        CreateNoWindow = false,
        WorkingDirectory = @"D:\AzCopy\bin\Debug\"
    };