1. Technology

Running C# Command Line Applications

Redirecting I/O so Console Input and Output Can be emulated


For writing small utility programs, C# is pretty good. When it comes to debugging command line utilities you have three alternatives:

  1. Run it from the command line and use < to redirect input. eg
    app < input.txt

  2. In the debugger add your own command line arguments to the Start options on the property tab. This also lets you specify the working
    directory, ie where it runs.

  3. Wrap it up in this code which redirects the standard input from a text file. it's my preferred solution.

  4.   using (StreamReader SR = new StreamReader(@"C:\dev\AboutBot\cs\maps\huge-room.txt")) {
        Console.SetIn(SR) ;
        string line;
        while ((line = SR.ReadLine()) != null)
             // Do something with line

The key here is the console.SetIn( method which switches the input to the TextReader device which is part of StreamReader. Wrapping this up in a Using block means that the file is properly closed, and the file handle released when the block is exited.

Want to Learn more about C#?

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. How To Do Things in C#
  6. Running Command Line Applications in C#

©2014 About.com. All rights reserved.