MystBin
/1ee0ed1a70658f8454 Created 6 months ago...
Raw
Program.cs Hide Copy Raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using CommandLine; class Program { static string? ReadLine(string prompt = "") { Console.Write(prompt); string result = ""; int input; while (true) { input = Console.Read(); if (input == 13) return result.Length > 0 ? result : null; result += (char)input; } } static void Main() { Console.Title = "Example CLI"; string? input; Dictionary<string, string> args; while (true) { input = ReadLine(">>> "); if (input == null) { Console.WriteLine(); continue; } args = CLI.ArgParser(input.Split(' '), ["echo", "close"]); Console.Write($"You wrote:\n[{string.Join(", ", args)}]" + "\n"); } } }
CLI.cs Hide Copy Raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
namespace CommandLine { public struct CLI { public static Dictionary<string, string> ArgParser(string[] argsFromCLI, string[] validArguments) { List<string> inputArgs = [.. argsFromCLI]; string[] args = inputArgs.Where(validArguments.Contains).ToArray(); Console.WriteLine($"Input args: [{string.Join(", ", inputArgs)}]"); Console.WriteLine($"args: [{string.Join(", ", args)}]"); List<int> indexes = []; HashSet<string> seenArgs = []; // Sanitise the arguments before processing them for (int i = 0; i < args.Length; i++) { string arg = args[i]; if (seenArgs.Contains(arg)) throw new Exception($"repeated argument '{arg}' found."); seenArgs.Add(arg); indexes.Add(inputArgs.IndexOf(arg)); } // Add the end of the list so we can get a substring // to the end of the string the same way we would with // the other values. indexes.Add(inputArgs.Count); Dictionary<string, string> convertedArgs = []; for (int x = 0; x < indexes.Count - 1; x++) { // Take the indexes in pairs int firstIndex = indexes[x]; int secondIndex = indexes[x + 1]; string argument = inputArgs[firstIndex]; string supplied = string.Join(' ', inputArgs[(firstIndex + 1) .. secondIndex]); convertedArgs.Add(argument, supplied); } return convertedArgs; } } }