使用C#中的参数执行命令行.exe

我正在尝试使用C#中的参数执行命令行程序。 我本以为,在C#中站起来并实现这一目标将是微不足道的,但即使使用本网站及其他网站上提供的所有资源,它也具有挑战性。 我很茫然,所以我会提供尽可能详细的信息。

我当前的方法和代码在下面,在调试器中变量命令具有以下值。

command = "C:\\Folder1\\Interfaces\\Folder2\\Common\\JREbin\\keytool.exe -import -noprompt -trustcacerts -alias myserver.us.goodstuff.world -file C:\\SSL_CERT.cer -storepass changeit -keystore keystore.jks" 

问题可能是我如何调用和格式化我在该变量命令中使用的字符串。

关于可能出现什么问题的任何想法?

 ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command); procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; Process process = new Process(); process.StartInfo = procStartInfo; process.Start(); string result = process.StandardOutput.ReadToEnd(); Console.WriteLine(result); 

一旦完成,我就不会在变量结果中找回任何信息或错误。

等待进程结束( 让它完成它的工作):

 ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command); procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; // wrap IDisposable into using (in order to release hProcess) using(Process process = new Process()) { process.StartInfo = procStartInfo; process.Start(); // Add this: wait until process does its work process.WaitForExit(); // and only then read the result string result = process.StandardOutput.ReadToEnd(); Console.WriteLine(result); } 

我意识到我可能遗漏了一些人将来可能需要解决这个问题的细节。

以下是运行时方法参数的值。 我对于对象ProcessStartInfo和Process需要正确站起来有些困惑我觉得其他人也可能。

exeDir =“C:\ folder1 \ folder2 \ bin \ keytool.exe”

args =“ – delete -noprompt -alias server.us.goodstuff.world -storepass changeit -keystore keystore.jks”

 public bool ExecuteCommand(string exeDir, string args) { try { ProcessStartInfo procStartInfo = new ProcessStartInfo(); procStartInfo.FileName = exeDir; procStartInfo.Arguments = args; procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; using (Process process = new Process()) { process.StartInfo = procStartInfo; process.Start(); process.WaitForExit(); string result = process.StandardOutput.ReadToEnd(); Console.WriteLine(result); } return true; } catch (Exception ex) { Console.WriteLine("*** Error occured executing the following commands."); Console.WriteLine(exeDir); Console.WriteLine(args); Console.WriteLine(ex.Message); return false; } 

在德米特里的协助和以下资源之间,

http://www.codeproject.com/Articles/25983/How-to-Execute-a-Command-in-C

我能够把它拼凑在一起。 谢谢!

当谈到从C#执行CLI进程时,它看起来似乎是一项简单的任务,但是在很久以后你甚至都注意到了很多陷阱。 例如,如果子进程将足够的数据写入stdout,则当前给出的两个答案都不起作用,如此处所述。

我编写了一个库,通过完全抽象Process交互,通过执行一个方法CliWrap来解决整个任务,从而简化了CLI的使用 。

您的代码将如下所示:

 var cli = new Cli("cmd"); var output = cli.Execute("/c " + command); var stdout = output.StandardOutput;