Main() and command-line arguments

When building console applications that take parameters, you can use the arguments passed to Main(string[] args). What would be a simple way to do something like example.exe --username=drpadawan --password=dontstealmypasswordplease. I have looked at some nuget packages but I feel it must be possible without a third party package.
7 Replies
Zendist
Zendist2y ago
Honestly, this is one of those things where I would always use a package. It's just so much simpler and you can get to the important stuff. Consider Dragonfruit or CommandLine.
Zendist
Zendist2y ago
GitHub
command-line-api/Your-first-app-with-System-CommandLine-DragonFruit...
Command line parsing, invocation, and rendering of terminal output. - command-line-api/Your-first-app-with-System-CommandLine-DragonFruit.md at main · dotnet/command-line-api
Zendist
Zendist2y ago
System.CommandLine overview
Learn how to develop and use command-line apps that are based on the System.CommandLine library
Zendist
Zendist2y ago
Dragonfruit is just a layer on top of System.CommandLine that negates the need to parse the arguments, such that you just create a type definition and it automatically parses args into that type, requiring less code.
Pobiega
Pobiega2y ago
If your program is a little more complicated, you might consider using an entire CLI host - such as CliFx or Spectre.Console.Cli this is significantly more complicated than just a main method, but if you support 10 subcommands and 30+ commandline switches, its amazing.
D.Mentia
D.Mentia2y ago
It's just simple string manipulation - something like
var argPairs = args.Select(x => string.Split(x.TrimStart('-'),'='));
foreach(var pair in argPairs)
yourValueDictionary[pair[0]] = pair[1];

// Then later...
var password = yourValueDictionary[Constants.Password];

// and somewhere else, like inside the Constants class...
public static const string Password = "password";
var argPairs = args.Select(x => string.Split(x.TrimStart('-'),'='));
foreach(var pair in argPairs)
yourValueDictionary[pair[0]] = pair[1];

// Then later...
var password = yourValueDictionary[Constants.Password];

// and somewhere else, like inside the Constants class...
public static const string Password = "password";
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View