Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom CMD Commands

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.

like image 308
Dan-Matei Mitreanu Avatar asked Jun 17 '26 05:06

Dan-Matei Mitreanu


1 Answers

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

like image 165
Evan L Avatar answered Jun 18 '26 19:06

Evan L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!