使用 C# 中的参数执行命令行 .exe [英] Executing Command line .exe with parameters in C#

查看:26
本文介绍了使用 C# 中的参数执行命令行 .exe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自 C# 的参数执行命令行程序.我原以为在 C# 中站出来并实现这一点是微不足道的,但即使使用本网站及其他网站上的所有可用资源,它也证明是具有挑战性的.我不知所措,所以我会提供尽可能多的细节.

I'm trying to execute a command line program with parameters from C#. I would have imagined that standing this up and making this happen would be trivial in C# but its proving challenging even with all the resources available on the this site and beyond. I'm at a loss so I will provide as much detail as possible.

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

My current approach and code is below and in the debugger the variable command has the following value.

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"

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

The problem may be how I am calling and formatting the string I use in that variable command.

对可能是什么问题有任何想法吗?

Any thoughts on what might be the issue?

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

一旦变量结果完成,我就不会返回任何信息或错误.

I get back no information or error in the variable result once its completes.

推荐答案

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

Wait for the process to end (let it do its work):

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

这篇关于使用 C# 中的参数执行命令行 .exe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆