473,396 Members | 1,992 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

redirecting standard output to a listbox

I'm trying to run a cmd.exe from my form with some arguments and have it output the standard output live to a listbox. I have got it running to the point where the cmd file runs correctly, and if I change the code a bit I get "System.IO.StreamReader" in my listbox, but not the actual output. This is my code:

Expand|Select|Wrap|Line Numbers
  1. private void startCmd(string cmdFileName, string argument)                  //startCmd test method 
  2.         {                                                           
  3.             var thread = new Thread(new ThreadStart(() =>
  4.             {
  5.                 Process p = new Process();                                                //create a new process for us to open our cmd line program
  6.  
  7.                 p.StartInfo.FileName = cmdFileName;                                       //use the given file name to seect the correct mining program
  8.                 p.StartInfo.Arguments = argument;               //add all the arguments we appended together above into a string
  9.                 p.StartInfo.UseShellExecute = false;                                      //don't use the shell to execute the cmd file                                           
  10.                 p.StartInfo.RedirectStandardOutput = true;                                //redirect the standard output
  11.                 p.StartInfo.RedirectStandardError = true;                                 //redirect standard errors
  12.                 p.StartInfo.CreateNoWindow = true;                                        //don't create a new window
  13.  
  14.                 Process[] pname = Process.GetProcessesByName("minerd");                   //check all processes and put into array
  15.                 if (pname.Length == 0)                                                    //test process name against length to see if it's running
  16.                 {
  17.                     p.Start();                                                            //if not running, start the program
  18.                     StreamReader sr = p.StandardOutput;                                   //read the programs output into a streamreader
  19.  
  20.  
  21.                     while (!p.HasExited)                                                  //while the program is still running
  22.                     {
  23.  
  24.                        // if (!sr.EndOfStream)                                               // TODO: This blocks the process for some reason...?
  25.                         {
  26.                             string procOutput = sr.ReadLine();
  27.                             // trying to do the control update directly will result in an invalid cross-thread operation exception
  28.                             // instead, we invoke the control update on the window thread using this.Invoke(...)
  29.                             this.Invoke(new Action<string>(s => { lbCpuOutput.Items.Add(procOutput); }), procOutput);
  30.                         }
  31.                         //else Thread.Sleep(20);                                                 // no input, so just wait for 20ms and check again
  32.                     }
  33.                 }
  34.                 else
  35.                 {
  36.                     MessageBox.Show("the program is already running");
  37.                 }
  38.  
  39.             }));
  40.  
  41.             thread.Start();
  42. }
Thank you for your help!
Jan 13 '14 #1
1 3812
I finally got it working, not need to reply.

For anyone else who was having issues, I got this code from here which helped out a ton:

Expand|Select|Wrap|Line Numbers
  1. SynchronizationContext _syncContext;
  2. MyForm()
  3. {
  4.     _syncContext = SynchronizationContext.Current;
  5. }
  6.  
  7. void StartProcess()
  8. {
  9.     var process = new Process
  10.     {
  11.         StartInfo = new ProcessStartInfo
  12.         {
  13.             FileName = "myProcess.exe",
  14.             UseShellExecute = false,
  15.             RedirectStandardOutput = true,
  16.             RedirectStandardError = true,
  17.         }
  18.     };
  19.  
  20.     process.OutputDataReceived += (sender, args) => Display(args.Data);
  21.     process.ErrorDataReceived += (sender, args) => Display(args.Data);
  22.  
  23.     process.Start();
  24.     process.BeginOutputReadLine();
  25.     process.BeginErrorReadLine();
  26.  
  27.     process.WaitForExit(); //you need this in order to flush the output buffer
  28. }
  29.  
  30. void Display(string output)
  31. {
  32.     _syncContext.Post(_ => myTextBox.AppendText(output), null);
  33. }
Jan 13 '14 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Marko Faldix | last post by:
Hello, with Python 2.3 I can write umlauts (a,o,u umlaut) to a file with this piece of code: import codecs f = codecs.open("klotentest.txt", "w", "latin-1") print >>f, unicode("My umlauts...
2
by: Max Berghammer | last post by:
Hi ! Is there any way to redirect the standard-outputstream or standard-errorstream of the currently running process ? I know that i can spawn a new process and redirect its standard-outputstream...
3
by: Rob Z | last post by:
I use popen in C++ to grab the standard output from Unix commands. Is there a similarly simple and fast way to grab standard error as well? I understand Python has different popen commands for...
2
by: Brian | last post by:
I'm running a dos program via System.Diagnostics.Process. The dos program is very picky about filenames and such, and so I want to show the output to the user so they can verify it did what it...
4
by: Zenon | last post by:
I have a C# application which interacts with an HP UNIX box via PSFTP. I have run in to a problem where the maximum amount of characters I can redirect is 1024. This number leads me to believe...
16
by: Zenon | last post by:
I have an application where I create a Plink process to communicate with an HP Unix box. The problem I am having is that while reading the redirected output, it seems to try to continue past the...
1
by: PiotrKolodziej | last post by:
Hi I have a process that output i need to save in file. Its a ping.exe. Iam sending 4 packets, and waiting for the process to exit. First i tried to add arguments to the proces in such a way: ...
3
by: mhmtzdmr | last post by:
Hi, I want to run an application and capture its standard output. But the following code does not generate any output. Can anyone see something wrong? Public Sub RunApp(ByVal myprocess As...
14
by: =?Utf-8?B?R2lkaQ==?= | last post by:
Hi, In my windows applicationm, i need to excute a batch file. this batch file throws some text and questions to the screen, i need to catch the standard Output, check if it's a question, in...
1
by: Ed Sexton | last post by:
I am writing a c program in which I would like to read the output from a second program which writes to the com2 port. Is there a way in Windows to redirect the com2 output to go to standard output...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.