Home › PowerShell › Passing Arguments to a Console App using C#
PowerShell · Oct 17, 2015 · 1 MIN READ

Passing Arguments to a Console App using C#

In this post, we will create a console app that accepts arguments or switches.

In Visual Studio, create a new console app:

The args parameter gives us what the user has entered, e.g:

sampleapp.exe -something /i dosomething

Add some code to print the arguments the user has provided. We will print the first 2 arguments:

Now, run the app and provide 2 arguments. We can see when we provide SampleArg1 and SampleArg2 as the first 2 arguments, these are printed out:

Knowing this, we can add switch or if statements to determine what to do when we encounter certain parameters, with prefixes such as “-“, “/” etc. For example, we can add code to look for a switch, such as “/l”:

[sourcecode language=”CSharp”] using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Carl.ConsoleAppArgs
{
class Program
{
static void Main(string[] args)
{
foreach (string arg in args)
{
if (arg.StartsWith("/"))
{
switch (arg.Substring(1))
{
case "j":
Console.WriteLine("You entered /j");
break;
case "l":
Console.WriteLine("You entered /l");
break;
default:
break;
}
}
}
Console.ReadLine();
}
}
}

[/sourcecode]

Running this, if we enter an unknown switch, nothing will happen. With a known switch such as /j, we get a response:

 

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert

Leave a Reply

Your email address will not be published. Required fields are marked *

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.