简体   繁体   English

从 C# 运行 .bat 文件

[英]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 .我面临一个奇怪的问题,我有一个 .bat 文件,其中包含重命名文件的代码,当我手动打开 .bat 文件时,它会执行上面写的重命名文件的操作,但是当我尝试打开时它从 C# 以编程方式,它不做任何事情,它只是打开文件并且不编译它写入的内容。 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 :我也知道如果你在 cmd 中输入路径并按 Enter 它将打开文件并编译它,所以我写道:

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 :我拍了一张应该运行 .bat 文件的 CMD 窗口的快照,我得到了错误:

ERROR : THE FILE SPECIFIED COULD NOT BE FOUND

but how ?但是怎么样? when i run the .bat file manually it works FINE!!!当我手动运行 .bat 文件时,它工作正常!!!

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.....请注意,变量myBatchFileName是 .bat 文件的实际名称.....

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():如果是这样,请使用 Process.Start() 的替代版本:

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

Make the first line of the batch file this:将批处理文件的第一行设为:

pushd %~dp1推%~dp1

This will set the batch files working directory.这将设置批处理文件的工作目录。

martyn马丁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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