In some cases, you just need to write a console application and want to be able to pass in different command line parameters as key/pairs. You can use the following C# Command Line Reader, which is simple enough, and easy to use (only 1 file, 1 class).
The full C# source code is available at github.
/*
Author: https://helloacm.com
Free to Use, donation is appreciated: https://helloacm.com/out/paypal
*/
using System;
using System.Collections.Generic;
namespace CommandLineParametersReader
{
public class SimpleCommandLineParametersReader
{
private readonly char SepChar = '=';
private string[] _args { get; }
private Dictionary<string, string> _dict { get; }
private bool CaseSensitive { get; }
public CommandLineParametersReader(string[] args, bool isCaseSesnive = false)
{
if (args == null)
{
throw new Exception("args should not be null");
}
_args = args;
CaseSensitive = isCaseSesnive;
_dict = new Dictionary<string, string>();
Process();
}
// Process Arguments into KeyPairs
private void Process()
{
foreach (var arg in _args)
{
var s = arg.Trim();
var ss = s.Split(new []{ SepChar }, 2, StringSplitOptions.RemoveEmptyEntries);
if (ss.Length <= 0) continue;
var key = ss[0];
if (!CaseSensitive)
{
key = key.ToLower();
}
var val = ss[1];
_dict[key] = val;
}
}
// Return the Key with a default value
public string Get(string key, string defaultvalue = "")
{
if (!CaseSensitive) { key = key.ToLower();}
return _dict.ContainsKey(key) ? _dict[key] : defaultvalue;
}
}
}
Example Usage:
var param = new SimpleCommandLineParametersReader(args);
param.CaseSensitive = True;
var input = param.Get("Input"); // suppose you have command line parameter "Input=InputFile"
var Output = param.Get("Output", "DefaultOutput");
The C++ version is also implemented, and can be found in this post.
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: How to Tell Browsers Re-update CSS/JS files when Files are Changed in WordPress?
Next Post: C++ Simple Command Line Parameters Reader