Skip to content

Instantly share code, notes, and snippets.

@redheadgektor
Created January 6, 2024 13:15
Show Gist options
  • Save redheadgektor/7263bf4933433152efb560b3087775b4 to your computer and use it in GitHub Desktop.
Save redheadgektor/7263bf4933433152efb560b3087775b4 to your computer and use it in GitHub Desktop.
Parsing Environment.GetCommandLineArgs()
using System;
using System.Collections.Generic;
[Serializable]
public class CommandLineHandler
{
[Serializable]
public struct CommandAndValue
{
public string command;
public string value;
public bool HasValue;
public CommandAndValue(string cmd, string value)
{
this.command = cmd;
this.value = value;
HasValue = value == null || value.Length == 0 ? false : true;
}
}
public List<CommandAndValue> list { get; private set; } = new List<CommandAndValue>();
public void Parse(string[] cmdline)
{
var count = cmdline.Length;
for (int cmd_index = 0; cmd_index < count; cmd_index++)
{
string c = cmdline[cmd_index];
if (c.StartsWith("-") || c.StartsWith("+"))
{
var cmd = c;
var arg = (cmd_index < count - 1) ? cmdline[cmd_index + 1] : string.Empty;
arg = string.Empty;
for (int arg_index = cmd_index + 1; arg_index < count; arg_index++)
{
if (cmdline[arg_index].StartsWith("-") || cmdline[arg_index].StartsWith("+"))
{
break;
}
else
{
var next_is_arg =
(arg_index < count - 1)
&& (
!cmdline[arg_index + 1].StartsWith("-")
|| !cmdline[arg_index + 1].StartsWith("+")
);
var next_is_cmd =
(arg_index < count - 1)
&& (
cmdline[arg_index + 1].StartsWith("-")
|| cmdline[arg_index + 1].StartsWith("+")
);
if (next_is_arg)
{
arg += next_is_cmd ? $"{cmdline[arg_index]}" : $"{cmdline[arg_index]} ";
}
else
{
arg += $"{cmdline[arg_index]}";
}
}
}
list.Add(new CommandAndValue(cmd, arg));
}
}
}
public bool FindCmd(string cmd, out string value)
{
value = string.Empty;
for (var i = 0; i < list.Count; i++)
{
if (list[i].command.Contains(cmd, StringComparison.OrdinalIgnoreCase))
{
value = list[i].value;
return true;
}
}
return false;
}
public bool HasCmd(string cmd)
{
for (var i = 0; i < list.Count; i++)
{
if (list[i].command.Contains(cmd, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
public CommandLineHandler(string[] cmd)
{
Parse(cmd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment