Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3597376
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T20:06:38+00:00 2026-05-18T20:06:38+00:00

I’m developing a C# application and I need to start an external console program

  • 0

I’m developing a C# application and I need to start an external console program to perform some tasks (extract files). What I need to do is to redirect the output of the console program. Code like this one does not work, because it raises events only when a new line is writen in the console program, but the one I use “updates” what’s shown in the console window, without writting any new lines. How can I raise an event every time the text in the console is updated? Or just get the output of the console program every X seconds? Thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T20:06:39+00:00Added an answer on May 18, 2026 at 8:06 pm

    I have had a very similar (possibly the exact) problem as you describe:

    1. I needed the console updates to be delivered to me asynchronously.
    2. I needed the updates to be detected regardless of whether a newline was input.

    What I ended up doing goes like this:

    1. Start an “endless” loop of calling StandardOutput.BaseStream.BeginRead.
    2. In the callback for BeginRead, check if the return value of EndRead is 0; this means that the console process has closed its output stream (i.e. will never write anything to standard output again).
    3. Since BeginRead forces you to use a constant-length buffer, check if the return value of EndRead is equal to the buffer size. This means that there may be more output waiting to be read, and it may be desirable (or even necessary) that this output is processed all in one piece. What I did was keep a StringBuilder around and append the output read so far. Whenever output is read but its length is < the buffer length, notify yourself (I do it with an event) that there is output, send the contents of the StringBuilder to the subscriber, and then clear it.

    However, in my case I was simply writing more stuff to the console’s standard output. I ‘m not sure what “updating” the output means in your case.

    Update: I just realized (isn’t explaining what you are doing a great learning experience?) that the logic outlined above has an off-by-one bug: If the length of the output read by BeginRead is exactly equal to the length of your buffer, then this logic will store the output in the StringBuilder and block while trying to see if there’s more output to append. The “current” output will only be sent back to you when/if more output is available, as part of a larger string.

    Obviously some method of guarding against this (or a biggish buffer plus faith in your powers of luck) is needed to do this 100% correctly.

    Update 2 (code):

    DISCLAIMER:
    This code is not production-ready. It is the result of me quickly hacking together a proof of concept solution to do what needed to be done. Please do not use it as it stands in your production application. If this code causes horrible things to happen to you, I will pretend someone else wrote it.

    public class ConsoleInputReadEventArgs : EventArgs
    {
        public ConsoleInputReadEventArgs(string input)
        {
            this.Input = input;
        }
    
        public string Input { get; private set; }
    }
    
    public interface IConsoleAutomator
    {
        StreamWriter StandardInput { get; }
    
        event EventHandler<ConsoleInputReadEventArgs> StandardInputRead;
    }
    
    public abstract class ConsoleAutomatorBase : IConsoleAutomator
    {
        protected readonly StringBuilder inputAccumulator = new StringBuilder();
    
        protected readonly byte[] buffer = new byte[256];
    
        protected volatile bool stopAutomation;
    
        public StreamWriter StandardInput { get; protected set; }
    
        protected StreamReader StandardOutput { get; set; }
    
        protected StreamReader StandardError { get; set; }
    
        public event EventHandler<ConsoleInputReadEventArgs> StandardInputRead;
    
        protected void BeginReadAsync()
        {
            if (!this.stopAutomation) {
                this.StandardOutput.BaseStream.BeginRead(this.buffer, 0, this.buffer.Length, this.ReadHappened, null);
            }
        }
    
        protected virtual void OnAutomationStopped()
        {
            this.stopAutomation = true;
            this.StandardOutput.DiscardBufferedData();
        }
    
        private void ReadHappened(IAsyncResult asyncResult)
        {
            var bytesRead = this.StandardOutput.BaseStream.EndRead(asyncResult);
            if (bytesRead == 0) {
                this.OnAutomationStopped();
                return;
            }
    
            var input = this.StandardOutput.CurrentEncoding.GetString(this.buffer, 0, bytesRead);
            this.inputAccumulator.Append(input);
    
            if (bytesRead < this.buffer.Length) {
                this.OnInputRead(this.inputAccumulator.ToString());
            }
    
            this.BeginReadAsync();
        }
    
        private void OnInputRead(string input)
        {
            var handler = this.StandardInputRead;
            if (handler == null) {
                return;
            }
    
            handler(this, new ConsoleInputReadEventArgs(input));
            this.inputAccumulator.Clear();
        }
    }
    
    public class ConsoleAutomator : ConsoleAutomatorBase, IConsoleAutomator
    {
        public ConsoleAutomator(StreamWriter standardInput, StreamReader standardOutput)
        {
            this.StandardInput = standardInput;
            this.StandardOutput = standardOutput;
        }
    
        public void StartAutomate()
        {
            this.stopAutomation = false;
            this.BeginReadAsync();
        }
    
        public void StopAutomation()
        {
            this.OnAutomationStopped();
        }
    }
    

    Used like so:

    var processStartInfo = new ProcessStartInfo
        {
            FileName = "myprocess.exe",
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            UseShellExecute = false,
        };
    
    var process = Process.Start(processStartInfo);
    var automator = new ConsoleAutomator(process.StandardInput, process.StandardOutput);
    
    // AutomatorStandardInputRead is your event handler
    automator.StandardInputRead += AutomatorStandardInputRead;
    automator.StartAutomate();
    
    // do whatever you want while that process is running
    process.WaitForExit();
    automator.StandardInputRead -= AutomatorStandardInputRead;
    process.Close();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have thousands of HTML files to process using Groovy/Java and I need to
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
Specifically, suppose I start with the string string =hello \'i am \' me And
In my XML file chapters tag has more chapter tag.i need to display chapters
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I need to clean up various Word 'smart' characters in user input, including but
I need a function that will clean a strings' special characters. I do NOT

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.