14.2. Developing Command Line–Driven Applications

We occasionally have a need to develop a command line–driven application—i.e., an application that doesn't have a formal GUI front-end for either soliciting input from the user or for displaying output to the user. Running a program from the command line is also useful during code development, because debugging messages can be written to appear on the console window. When building command line–driven applications, we need to be able to

  • Accept input, either by

    • Reading data from the command line, in the form of command-line arguments, or

    • Accepting keyboard input as typed by the user

  • Display textual messages to the user, including both prompts for input as well as feedback on operations that have been performed

14.2.1. Reading Command-Line Arguments

As mentioned earlier, as a "driver" method for the program, the Main method can accept command-line arguments. Such arguments are typically used to either pass in small amounts of data or control some aspect of the program's execution.

Command-line arguments can be included as part of the command to execute a C# application, following the name of the class that contains the Main method that will serve as the entry point for the program on the command line. For example, if we wanted to provide an executable named SimpleProgram.exe with the command-line arguments Jackson, ABC, and 123, we would type the following command to run the program:

SimpleProgram Jackson ABC 123

Such data gets passed to the Main method of the C# program as a string array called args (or whatever else we wish to name it, as indicated by the Main method's parameter list). To accept command-line arguments, therefore, a program must use one of the two forms of the Main method that takes a string array as a parameter:

static void Main(string[] args)
static int Main(string[] args)

The args array is automatically sized to hold however many arguments are provided on the command line when the program is invoked. In the previous SimpleProgram invocation, the args array would contain three entries: the string "Jackson" would be placed as the first element of the args array (args[0]), the string "ABC" would be the next element of args, and the string "123" would be the last element. Command-line arguments surrounded by double quotes are taken literally. For example, if the following command were executed:

SimpleProgram "Zachary Palmer"

the first command-line argument, args[0], would have the value "Zachary Palmer".

Inside the Main method, we can do with args whatever we'd do with any other array—for example, determine its length, manipulate individual string items within the array, and so forth. The program that follows illustrates some of the things that we might wish to do with command-line arguments:

// FruitExample.cs

// This program is intended to illustrate command-line argument
// passing.

using System;

public class FruitExample {
  // The args[] array is automatically initialized when the
  // program is run from the command prompt with whatever
  // (space-separated) values ('arguments') we've typed on the
  // command line after the program name.
  //

static void Main(string[] args) {
  // Let's print out a few things.
  Console.WriteLine("The args array contains " + args.Length +
                    " entries." );

  // Only execute this next block of code if the array isn't
  // empty. The Length property returns the number of elements
  // in the array.
  if (args.Length > 0) {
    int last = args.Length - 1;
    Console.WriteLine("The last array entry is: " + args[last]);

    // Every string has a Length property, as well, that
    // contains the number of characters in the string.
    Console.WriteLine("The last array entry is " +
                       args[last].Length +" characters long.");
  }
  else {
    Console.WriteLine("No command line arguments detected.");
  }
 }
}

When this program is run from the command line as follows:

FruitExample apple banana cherry

it produces the following output:

The args array contains 3 entries.
The last array entry is: cherry
The last array entry is 6 characters long.

14.2.2. Accepting Keyboard Input

Most applications receive information either directly from users via an application's graphical user interface or by reading information from a file or database. But, until you've learned how to program such things in C# in Chapters 15 and 16, it's handy to know how to prompt for textual input from the command-line window.

To read keyboard input, we'll turn once again to the Console class from the System namespace. The Console class declares a ReadLine method that can be used to read keyboard input.

public static string ReadLine()

Data is read character by character but is buffered internally by this method until the Enter key is pressed, at which point an entire line of input is returned by the method as a string.

The ReadLine method reads data from the standard input/output (I/O) stream, which in most cases is associated with the keyboard. The ReadLine method can generate an IOException, so calls to the method should be enclosed in a try block.

Here is a simple example that illustrates reading data from the keyboard using the ReadLine method; we'll present the program in its entirety first, then narrate it in step-by-step fashion.

using System;
using System.IO;

public class KeyboardDemo
{
  static void Main() {
    string name = "";

    try {
      // Prompt the user for input; note the use of
						// Write() vs. WriteLine(), so that the prompt will
						// be displayed on the same line as the text entered
						// by the user.
      Console.Write("Enter your name: ");

      // Read their response from the keyboard.
      name = Console.ReadLine();
    }
    catch (IOException ioe) {
      Console.WriteLine("IO Exception occurred: " + ioe);
    }

    // Display the input back as a test.
    Console.WriteLine("Name entered was " + name);
  }
}

Stepping through the code:

  • When the KeyboardDemo program is run, the user is prompted to enter his or her name via a call to the Console.Write method:

    Console.Write("Enter your name: ");

    Note our use of Write vs. WriteLine, so that the prompt will be displayed on the same line as the text entered by the user.

  • The value of a local string variable called name is set to the string value returned by the ReadLine method:

    name = Console.ReadLine();

    This operation is performed inside a try block.

  • A catch clause is provided to catch IOExceptions. We'll cover exception handling in detail in Chapter 15, but for now just consider the catch clause as a safety net that lets the program keep running if something goes wrong with one of the I/O operations.

Running this program would produce the following results (bold text reflects input by the user):

Enter your name: Jackie Chan
Name entered was Jackie Chan

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset