Running a batch file with arguments from C #

I have a batch file like this

@echo off xcopy /e %1 %2 

I have C # code as follows:

 string MyBatchFile = @"C:\Program Files (x86)\MybatchFile.bat"; string _sourcePath = @"C:\FolderToCopy"; string _tempTargetPath = @"C:\TargetFolder\"; var process = new Process { StartInfo = { Arguments = string.Format("{0} {1}", _sourcePath, _tempTargetPath) } }; process.StartInfo.FileName = MyBatchFile; bool b = process.Start(); 

I expect this to copy the source files to the destination location. But nothing happens. My console window also does not stay long enough for me to see the error. Can anyone help with this. I am new to batch file processing.

Edit

By adding pause to the end of the batch file. Ability to reproduce errors. Getting error like

 Files not found - Program 

Running a batch file directly works fine. Just noticed ... when the source path has some spaces .... I get an error

+6
source share
3 answers

How about quoting an argument?

 Arguments = String.Format("\"{0}\" \"{1}\"", _sourcePath, _tempTargetPath) … 
+8
source

The .bat file is a text file, in order to execute it, you must start the cmd process. Start like this:

 System.Diagnostics.Process.Start("cmd.exe", "/c yourbatch.bat"); 

Additional arguments are possible. Try this without C #, in the cmd window or in the Run dialog box.

+5
source

to try

 string MyBatchFile = @"C:\MybatchFile.bat"; string _sourcePath = @"C:\FolderToCopy\*.*"; string _tempTargetPath = @"C:\TargetFolder\"; 

i.e. add *.* to the source path

and add the third line pause to the batch file

 @echo off copy /e %1 %2 pause 
+2
source

All Articles