开发者

C# Problem with Running Console Command

开发者 https://www.devze.com 2023-02-07 02:58 出处:网络
Hi i\'m trying to run a dos command in c#. When I run the command from console it works fine. But I can\'t get the output of the command. Code is below.

Hi i'm trying to run a dos command in c#. 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 runPro开发者_JS百科cessStartInfo = 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. What might be the problem?


You don't need to call to cmd /c

You can call to java directly.

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.


Try reading the StandardError stream. Sometimes Java puts the output text in the error stream.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号