Running batch file with arguments from C#
Solution 1
What about quoting argument?
Arguments = String.Format("\"{0}\" \"{1}\"", _sourcePath, _tempTargetPath) …
Solution 2
.bat file is a text file, in order to execute it, you should start cmd process. Start it like this:
System.Diagnostics.Process.Start("cmd.exe", "/c yourbatch.bat");
Additional arguments may follow. Try this without c#, in a cmd window, or Run dialog.
Solution 3
try
string MyBatchFile = @"C:\MybatchFile.bat";
string _sourcePath = @"C:\FolderToCopy\*.*";
string _tempTargetPath = @"C:\TargetFolder\";
i.e. add *.*
to the source path
and add a 3rd line pause
to the batch file
@echo off
copy /e %1 %2
pause
Sandy
Enthusiast in technology world and fascinated by new entrepreneurs. Strongly believe in innovation and creativity and looking forward to be a part of it.
Updated on July 09, 2022Comments
-
Sandy almost 2 years
I have a batch file like this
@echo off xcopy /e %1 %2
I have my 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 target location. But nothing happens. My console window also does not stay for enough time so that I can see the error. Can anyone guide to achieve this. I am new in batch files processing.
Edit
By adding a
pause
in the end of batch file. Able to reproduce error. Getting error asFiles not found - Program
Running batch file directly does work fine. Just now noticed......when source path has any spaces....I am getting error
-
Sandy over 11 yearsthanks.....getting error as
Files not found - Program
. Edited my post with sourcepath changed. -
qujck over 11 yearsThat may be due to the paths - are there any files in the source folder (and you do need
*.*
for the xcopy command) - I have it running here. -
Sandy over 11 yearsI have files in Source path. Running batch file directly does work fine. Just now noticed......when source path has any spaces....I am getting error
-
qujck over 11 yearspaths with spaces will need to be wrapped in "'s or use the DOS 8 character path.