3

Is it possible to create custom Command Prompt parameters for an application written and compiled in Visual Studio C#. I want the users of my application to be able to do stuff in it just by command line.

For example, if the user types in CMD application_name.exe -parameter to do the code that was assigned to parameter.

Jeff B
  • 8,572
  • 17
  • 61
  • 140
  • There are built-in ways to do this of course, but I like to use [docopt.net](https://github.com/docopt/docopt.net). It's available in nuget. – Jeff B Mar 04 '14 at 17:41

3 Answers3

7

Yes, this is what string[] args is for in Program.cs.

The easiest way to ensure you have everything you need is to create your application from the Console Application template in Visual Studio.

To do this:

  1. Go to File -> New Project...
  2. Select Console Application from the list of available templates
  3. Name your Solution
  4. Hit OK to finish creating the Project

This will ensure you have all the references needed and that the Program.cs class is setup properly.

Here is a psuedo example of what you can do in the Main method of your program in order to accept parameters at the command line:

static void Main(string[] args)
{
    if (args.Length <= 0) //Checking the Length helps avoid NullReferenceException at args[0]
    {
        //Default behavior of your program without parameters
    }
    else
    {
        if (args[0] == "/?")
        {
            //Show Help Manual
        }
        if (args[0] == "/d")
        {
            //Do something else
        }
        //etc
    }
}

Then at the command prompt the user can type:

yourProgamName.exe /?
yourProgramName.exe /d

As mentioned in an answer that was removed, there is a great library for handling complex Command Line options Here:

NDesk Options

Evan L
  • 3,805
  • 1
  • 22
  • 31
0

That is what the "args" parameter is for in your main method.

If your users run "application_name.exe -parameter" then args[0] will be "-parameter". You can use this to branch your application to the correct code.

Check out this question to see examples and good libraries for handling lots of command line parameters/arguments.

Community
  • 1
  • 1
Talon876
  • 1,482
  • 11
  • 17
0

and if you don't have access to you main() for some reason, you can get your command line from Environment.CommandLine.

LB2
  • 4,802
  • 19
  • 35