简体   繁体   中英

C# .net i need to record the output of the file.?

i have this program i need to make, where it runs a bat file. i got that far, so when i click the button it opens the bat. but 3 problems i encountered i have been trying to resolve for a few days now, the problem is that i need to get the output of the .bat and display it in a textbox, i got that, but it only displays the first and least line... then i need to run the .bat in the background. so you don't see the window. then i also need to be able to hit a second button to close it. the bat is a constant update, lets just say it reads a number then 5 seconds later adds 1 to that number and displays it again. and does this over and over till you close it. that would be a simple description of this

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "C:\\Users/jwoow/Desktop/Server/run.bat";
p.Start();                    
string output = p.StandardOutput.ReadToEnd();
this.RunResults.Text = output;
p.WaitForExit();

Try to just ask one specific question at a time.

Stopping the process

You can end the process by calling the CloseMainWindow . Method on the Process object. Like this:

p.CloseMainWindow();

Just hook up the button event handler and call this method to end the process.

Displaying outputted lines in a message box

The ReadToEnd method blocks until all lines are read. You will probably rather need a loop to read line at a time, like this:

StreamReader output = p.StandardOutput;
while (output.EndOfStream == false)
{
    var line = output.ReadLine();
    MessageBox.Show(line);
}

Avoid showing a console window

To avoid showing a console window you will need to add this before starting the process

p.StartInfo.CreateNoWindow = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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