Run .bat file from C#

廉价感情. 提交于 2020-01-15 06:06:47

问题


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!!!


回答1:


you may try like this. ProcessStartInfo

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



回答2:


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);



回答3:


Make the first line of the batch file this:

pushd %~dp1

This will set the batch files working directory.

martyn




回答4:


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.....


来源:https://stackoverflow.com/questions/9322516/run-bat-file-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!