C sharp使用cmd调用Java
本文关键字:调用 Java cmd 使用 sharp | 更新日期: 2023-09-27 18:11:11
我正在尝试编写一个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;
}
和main方法
我叫
string result = StartCmdProcess(new string[] { "java -version" });
Console.WriteLine(result);
当我调用"java"时,它工作得很好,并输出了所有应该打印的内容。
但是,当我输入java -version这样的参数时,它就不起作用了。
有谁知道这个问题是怎么回事吗?
如果有人能帮助我,我将非常感激:)
EDITED:调用的结果实际上是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();
您需要修改您的方法以使用cmd参数,如下所示
public static string StartCmdProcess(string[] cmd)
{
System.Diagnostics.Process p = new System.Diagnostics.Process
{
StartInfo =
{
FileName = cmd[0],
Arguments = cmd.Length>1?cmd[1]:"",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
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;
}