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

时间:2016-05-31 15:01:28

标签: c# cmd keystore

我尝试使用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);

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

3 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:0)

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

以下是运行时方法参数的值。我对于对象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

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

答案 2 :(得分:0)

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

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

您的代码将如下所示:

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