运行控制台命令的C#问题

时间:2011-01-26 22:50:18

标签: c# console

您好我正在尝试在c#中运行dos命令。当我从控制台运行命令时它工作正常。但我无法得到命令的输出。代码如下。

String runCommand = "-classpath C:\\Users\\ZZZ\\Desktop\\javatest Javatest >C:\\outt.txt";
ProcessStartInfo runProcessStartInfo = new ProcessStartInfo("java.exe", runCommand);
runProcessStartInfo.RedirectStandardOutput = true;
runProcessStartInfo.UseShellExecute = false;
runProcessStartInfo.CreateNoWindow = true;

Process runProcess = new Process();
runProcess.StartInfo = runProcessStartInfo;
runProcess.Start();

StreamReader output = runProcess.StandardOutput;  
OutputTextBox.Text = output.ReadToEnd();

runProcess.WaitForExit();

此外,当我将runCommand设置为类似“dir”时,它工作正常。可能是什么问题?

3 个答案:

答案 0 :(得分:3)

您无需拨打cmd / c

您可以直接调用java。

ProcessStartInfo runProcessStartInfo = new ProcessStartInfo(
              "java.exe", "-classpath C:\\Users\\ZZZ\\Desktop\\javatest Javatest")
runProcessStartInfo.RedirectStandardOutput = true;
runProcessStartInfo.UseShellExecute = false;
runProcessStartInfo.CreateNoWindow = true;

Process runProcess = new Process();
runProcess.StartInfo = runProcessStartInfo;
string output = p.StandardOutput.ReadToEnd();
runProcess.WaitForExit();
runProcess.Close();


OutputTextBox.Text = output;

答案 1 :(得分:1)

您还需要确保等待程序退出。你可以这样做:

runProcess.Start();

using (StreamReader output = runProcess.StandardOutput)
{
    OutputTextBox.text = output.ReadToEnd();
}

runProcess.WaitForExit();

当然,您必须首先确保您的java程序正在写入标准输出,并且它不需要任何用户输入即可完成运行。

答案 2 :(得分:0)

尝试阅读StandardError流。有时,Java会将输出文本放在错误流中。

String runCommand = "-classpath C:\\Users\\ZZZ\\Desktop\\javatest Javatest >C:\\outt.txt";
ProcessStartInfo runProcessStartInfo = new ProcessStartInfo("java.exe", runCommand);
runProcessStartInfo.RedirectStandardError = true;
runProcessStartInfo.UseShellExecute = false;
runProcessStartInfo.CreateNoWindow = true;

Process runProcess = new Process();
runProcess.StartInfo = runProcessStartInfo;
runProcess.Start();

StreamReader output = runProcess.StandardError;  
OutputTextBox.Text = output.ReadToEnd();

runProcess.WaitForExit();