Search code examples
c#pathescapingbackslashxcopy

How to pass a path as an argument to Process.Start


the following code speaks for itself. When I try to xcopy a local folder to a networkshare, the paths get all messed up and CMD can't interpet correctly the backslashes. Any suggestions are welcome, already tried everything I found on the web (been stuck almost for 2 hours on this):

string command = "xcopy /s " + @"C:\Users\Me\Desktop\TempExtract\MyApp\*.* " + @"\\TestShare\SharedFolder\Applications\ /Y /I";
Process Processo = new Process();
ProcessStartInfo Xcopy = new ProcessStartInfo("cmd.exe");
Xcopy.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
Xcopy.Arguments = command;
Processo = Process.Start(Xcopy);
Processo.WaitForExit();

The problem here is that "Arguments" can't decode "\\" to "\" so my paths are like:

C:\\Users\\Me\\Desktop\\TempExtract\\MyApp\\*.*

And CMD can't interpert double backslashes :( help!


Solution

  • I think the problem lies in the way you setup ProcessStartInfo. So command should be:

    string command = @"C:\Users\Me\Desktop\TempExtract\MyApp\*.* " + @"\\TestShare\SharedFolder\Applications\ /Y /I";
    

    and add

    Xcopy.FileName = "xcopy";
    

    this is what worked for me:

    using System.Diagnostics;
    
    class Program
    {
        static void Main(string[] args)
        {
            var command = @"C:\Users\Me\Desktop\TempExtract\MyApp\*.* " + @"\\TestShare\SharedFolder\Applications\ /Y /I";
            var Processo = new Process();
            var Xcopy = new ProcessStartInfo("cmd.exe")
            {
                Arguments = command,
                FileName = "xcopy",
                UseShellExecute = false
            };
            Processo = Process.Start(Xcopy);
            Processo.WaitForExit();
        }
    }