简体   繁体   中英

Run .bat file from C#

i am facing a strange issue , i have a .bat file which contains a code for renaming a file , when i open the .bat file manually it does what it is written on it which is renaming a file , but when i try to open it programtically from C# , it doesnt do anything , it jsut open the file and do not compile what it is written into . i typed that code :

Process.Start(@"file.bat");

I also knew if you typed the path into cmd and pressed enter it will open the file and compile it , so i wrote that :

ProcessStartInfo psi3 = new ProcessStartInfo("cmd", "/c " + '"'+"D:\\my Work\\My Soft\\CA Delete\\CA Delete\\bin\\Debug\\file.bat"+'"');
Process p3 = Process.Start(psi3);
p3.WaitForExit()

But still the same issue : the file is being opened but never does what it is written into it.

EDIT : [I Figured why]

I took a snap shot of the CMD windows that should run the .bat file and i got ERROR :

ERROR : THE FILE SPECIFIED COULD NOT BE FOUND

but how ? when i run the .bat file manually it works FINE!!!

This should work for you:

String myBatchFileName = "name_of_file.bat";
System.Diagnostics.Process.Start(myBatchFileName);
  • Note that variable myBatchFileName is the actual name of .bat file.....

you may try like this. ProcessStartInfo

psi3.RedirectStandardError= true;
psi3 .RedirectStandardOutput= true;
psi3.UseShellExecute= false;

You may be requiring additional admin previleges to execute what is intended in the Batch file. If so, use the alternative version of Process.Start():

Start(string fileName, string arguments, string userName, SecureString password, string domain);

Make the first line of the batch file this:

pushd %~dp1

This will set the batch files working directory.

martyn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM