我正在尝试编写一个 C Sharp 程序来调用 jar 文件。
我已经搜索了很多关于此类问题的解决方案,但我就是无法弄清楚。
这是我的情况,在真正调用我的jar文件之前,我尝试调用java -version进行测试。
这是一个使用参数 cmd 执行命令行的方法
public static string StartCmdProcess(string[] cmd)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.AutoFlush = true;
for (int i = 0; i < cmd.Length; i++)
{
p.StandardInput.WriteLine(cmd[i].ToString());
}
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
return strRst;
}
在我的主要方法中
我打电话
string result = StartCmdProcess(new string[] { "java -version" });
Console.WriteLine(result);
当我调用“java”时,它工作正常并输出应该打印的所有内容。
但是,当我将参数设置为 java -version 时,它就不起作用了。
有人知道这个问题出在哪里吗?
如果有人能提供帮助,我们将不胜感激:)
已编辑:调用的结果实际上转到 StandardError 而不是 StandardOutput,但这非常连线。有人知道为什么吗?
public static string StartCmdProcess(string[] cmd)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.AutoFlush = true;
for (int i = 0; i < cmd.Length; i++)
{
p.StandardInput.WriteLine(cmd[i].ToString());
}
p.StandardInput.WriteLine("exit");
strRst.Append(p.StandardOutput.ReadToEnd()).Append(p.StandardError.ReadToEnd());
p.WaitForExit();
p.Close();
return strRst.ToString();
}
最佳答案
您需要将参数与命令分开设置。
p.StartInfo.FileName = "java";
p.StartInfo.Arguments = "-version";
当我测试这个时,输出被重定向,但它来自标准错误而不是标准输出。不确定为什么,但您可以像这样返回两个流:
StringBuilder strRst = new StringBuilder();
strRst.AppendLine(p.StandardOutput.ReadToEnd());
strRst.AppendLine(p.StandardError.ReadToEnd());
p.WaitForExit();
p.Close();
return strRst.ToString();
关于c# - C Sharp 使用 cmd 调用 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16234196/