#961 – Retrieving Command Line and Path to Executable

You can easily get information about the full command used to launch your application, as well as the path to the executable containing your code.

  • Environment.CommandLine is a string containing the full command line that launched your application
  • Environment.CurrentDirectory is a string containing the full path to the current working directory (which may be different from the directory containing your application)
  • Assembly.GetExecutingAssembly().CodeBase is a string containing the full path to the executable or DLL containing the code that is currently executing

For example:

            Console.WriteLine("Your full command line was:");
            Console.WriteLine(string.Format("  {0}", Environment.CommandLine));

            Console.WriteLine("Current working directory is:");
            Console.WriteLine(string.Format("  {0}", Environment.CurrentDirectory));

            // Requires: using System.Reflection;
            Console.WriteLine("Full path to executable:");
            Console.WriteLine(string.Format("  {0}", Assembly.GetExecutingAssembly().CodeBase));

If we launch the application as follows:
961-001
We’ll see the following output:
961-002

Advertisements

#13 – Specify Command Line Arguments in Visual Studio 2010

You’d normally pass command line arguments to your program when you invoke it from the command line.  However, for testing purposes, you may want to specify command line arguments that get passed to the program when you run it from the debugger.  You can do this in the Project Properties window, on the Debug tab.

Note that:

  • You can do this for all project types, e.g. console app, Win Forms, WPF
  • You can specify different arguments for Debug vs. Release mode
  • These arguments will be used only when running from the debugger

#12 – Read Command Line Arguments

If you are calling your C# program from the command line, you can pass in one or more command line arguments.  In your program, you can access these arguments by defining the Main function to accept a string array as a parameter and then iterating through the array to read the parameters.

static void Main(string[] args)
{
    // Ex 1: List all arguments
    foreach (string arg in args)
        Console.WriteLine(string.Format("Arg: [{0}]", arg));

    // Ex 2: Use 1st argument as filename
    if (args.Length > 0)
        Console.WriteLine(string.Format("File={0}", args[0]));
}