I have a console application called MyTool.exe
What is the simplest way to collect the named arguments passed to this console applicaiton and then to put them in a
I don't see why this code is bad? hova?
var arguments = new Dictionary<string, string>();
foreach (var item in Environment.GetCommandLineArgs())
{
try
{
var parts = item.Split('=');
arguments.Add(parts[0], parts[1]);
}
catch (Exception ex)
{
// your error handling here....
}
Here's how this can be done in the most simple way:
static void Main(string[] args)
{
var arguments = new Dictionary<string, string>();
foreach (string argument in args)
{
string[] splitted = argument.Split('=');
if (splitted.Length == 2)
{
arguments[splitted[0]] = splitted[1];
}
}
}
Note that:
if you have a "=" in your parameter values, a safer option would be:
private static Dictionary<string, string> ResolveArguments(string[] args)
{
if (args == null)
return null;
if (args.Length > 1)
{
var arguments = new Dictionary<string, string>();
foreach (string argument in args)
{
int idx = argument.IndexOf('=');
if (idx > 0)
arguments[argument.Substring(0, idx)] = argument.Substring(idx+1);
}
return arguments;
}
return null;
}
Use this Nuget package
Takes seconds to configure and adds instant professional touch to your application.
// Define a class to receive parsed values
class Options {
[Option('r', "read", Required = true,
HelpText = "Input file to be processed.")]
public string InputFile { get; set; }
[Option('v', "verbose", DefaultValue = true,
HelpText = "Prints all messages to standard output.")]
public bool Verbose { get; set; }
[ParserState]
public IParserState LastParserState { get; set; }
[HelpOption]
public string GetUsage() {
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
// Consume them
static void Main(string[] args) {
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options)) {
// Values are available here
if (options.Verbose) Console.WriteLine("Filename: {0}", options.InputFile);
}
}