简体   繁体   English

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

[英]C# Problem with Running Console Command

Hi i'm trying to run a dos command in c#. 嗨,我正在尝试在c#中运行dos命令。 When I run the command from console it works fine. 当我从控制台运行命令时它工作正常。 But I can't get the output of the command. 但我无法得到命令的输出。 Code is below. 代码如下。

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

Also when i set the runCommand to sth like "dir" it works fine. 此外,当我将runCommand设置为像“dir”一样,它工作正常。 What might be the problem? 可能是什么问题?

You don't need to call to cmd /c 您无需调用cmd / c

You can call to java directly. 你可以直接调用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;

You will need to make sure you wait for the program to exit, as well. 您还需要确保等待程序退出。 You can do something like this: 你可以这样做:

runProcess.Start();

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

runProcess.WaitForExit();

Of course, you will have to make sure that your java program is writing to standard output in the first place, and that it doesn't require any user input in order to finish running. 当然,您必须首先确保您的java程序正在写入标准输出,并且它不需要任何用户输入才能完成运行。

Try reading the StandardError stream. 尝试阅读StandardError流。 Sometimes Java puts the output text in the error stream. 有时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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM