This is a simple tutorial on passing arguments or parameter values from command line to a console application written in C#. Using the example below you should be able to edit and expand on the logic to fit your own needs.
First you’ll need to create a new Visual Studio C# console application, to do so follow these steps:
To create and run a console application
-
Start Visual Studio.
- On the menu bar, choose File, New, Project.
- Expand Installed, expand Templates, expand Visual C#, and then choose Console Application.
- In the Name box, specify a name for your project, and then choose the OK button.
- If Program.cs isn’t open in the Code Editor, open the shortcut menu for Program.cs in Solution Explorer, and then choose View Code.
-
Replace the contents of Program.cs with the following code.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestArgsInput { class Program { static void Main(string[] args) { if (args.Length == 0) { // Display message to user to provide parameters. System.Console.WriteLine("Please enter parameter values."); Console.Read(); } else { // Loop through array to list args parameters. for (int i = 0; i < args.Length; i++) { Console.Write(args[i] + Environment.NewLine); } // Keep the console window open after the program has run. Console.Read(); } } } }
The Main method is the entry point of a C# application. When the application is started, the Main method is the first method that is invoked.
The parameter of the Main method is a String array that represents the command-line arguments. Usually you determine whether arguments exist by testing the Length property as in the example above.
When run the example above will list out the parameters you have provided to the command window. The delimiter for command line separating arguments or parameter values is a single space. For example the following would be interpreted as two arguments or parameter values:
“This is parameter 1” “This is parameter 2”
If the arguments were not enclosed by double quotes each word would be considered an argument.
To pass arguments to the console application when testing the application logic the arguments can be written into the debug section of the project properties as shown below.