Chaque fois que je dois créer une application du type console, c’est le même problème.
Alors, je publie la version que je vais utiliser sur toutes mes applications. Effet, j’ai analysé plusieurs solutions, et détails techniques de chaque solution et j’ai fini pour choisir une solution publiée sur CodeProject.
Ma version de la solution est normalisée selon le standard du Reshaper, et il y a un *petit* changement de l’expression régulier.
1
2using System;
3
4namespace MyConsoleApplication
5{
6 class Program
7 {
8 #region Private Static Methods
9
10 private static void HowToUse()
11 {
12 Console.WriteLine("--------------------");
13 Console.WriteLine("Syntax : ");
14 Console.WriteLine("");
15 Console.WriteLine("MyConsoleApplication /myparam1=value1 /myparamBool /mypar2 /myvalueX=C:\\temp\\");
16 Console.WriteLine("");
17 Console.WriteLine("--------------------");
18 }
19
20 static void Main(string[] args)
21 {
22 Arguments commandLine;
23 commandLine = new Arguments(args);
24
25 //commandLine line : /myparam1=TestValue1 /myparamBool
26 if (commandLine["myparam1"].HasValue)
27 {
28 Console.WriteLine(commandLine["myparam1"].Value);
29 }
30 Console.WriteLine(commandLine["myparamBool"].ValueBool ? "has parameter" : "no parameter");
31
32 ShowArguments(commandLine);
33 WaitConfirmation();
34 }
35
36 private static void ShowArguments(Arguments commandLine)
37 {
38 const string message = @"::
39 :: Parameters :
40 ::";
41
42 Console.WriteLine(message);
43 if (commandLine.Parameters.Count == 0)
44 {
45 Console.WriteLine("** No parameters **");
46 HowToUse();
47 }
48
49 foreach (var c in commandLine.Parameters)
50 {
51 Console.WriteLine(" " + (c.HasValue ? string.Format("/{0}={1}", c.Name, c.Value) : string.Format("/{0}", c.Name)));
52 }
53 Console.WriteLine("");
54 }
55
56 private static void WaitConfirmation()
57 {
58 Console.WriteLine("\r\nPress a key to continue: ");
59 ConsoleKeyInfo cki = Console.ReadKey(true);
60 }
61
62 #endregion Private Static Methods
63 }
64}
Link de la solution: http://www.codeproject.com/Articles/3111/C-NET-Command-Line-Arguments-Parser
Reshaper: https://www.jetbrains.com/resharper/
Class Arguments
1
2 /// <summary>
3 /// Command line - Arguments parser
4 /// Created using VisualStudio 2013
5 /// <a href="http://www.codeproject.com/Articles/3111/C-NET-Command-Line-Arguments-Parser">http://www.codeproject.com/Articles/3111/C-NET-Command-Line-Arguments-Parser</a>
6 /// </summary>
7 public class Arguments
8 {
9 #region Private Read-Only Members
10
11 private readonly ArgumentType _defaultParameterNull = new ArgumentType();
12 private readonly System.Collections.Generic.List<ArgumentType> _parameters;
13
14 #endregion Private Read-Only Members
15
16 #region Public Constructors
17
18 public Arguments(System.Collections.Generic.IEnumerable<string> args)
19 {
20 //_parameters = new System.Collections.Specialized.StringDictionary();
21 _parameters = new System.Collections.Generic.List<ArgumentType>();
22 System.Text.RegularExpressions.Regex spliter = new System.Text.RegularExpressions.Regex(@"^-{1,2}|^/|=|:", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled);
23
24 System.Text.RegularExpressions.Regex remover = new System.Text.RegularExpressions.Regex(@"^['""]?(.*?)['""]?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled);
25
26 string parameter = null;
27 string[] parts;
28
29 // Valid parameters forms:
30 // {-,/,--}param{ ,=,:}((",')value(",'))
31 // Examples:
32 // -param1 value1 --param2 /param3:"Test-:-work"
33 // /param4=happy -param5 '--=nice=--'
34 foreach (string txt in args)
35 {
36 // Look for new parameters (-,/ or --) and a
37 // possible enclosed value (=,:)
38 parts = spliter.Split(txt, 3);
39
40 switch (parts.Length)
41 {
42 // Found a value (for the last parameter
43 // found (space separator))
44 case 1:
45 if (parameter != null)
46 {
47 //if (!_parameters.ContainsKey(parameter))
48 if (!Parameters.Exists(p => System.String.Equals(p.Name, parameter, System.StringComparison.CurrentCultureIgnoreCase)))
49 {
50 parts[0] =
51 remover.Replace(parts[0], "$1");
52
53 //_parameters.Add(parameter, parts[0]);
54 Parameters.Add(new ArgumentType(parameter, parts[0]));
55
56 }
57 parameter = null;
58 }
59 // else Error: no parameter waiting for a value (skipped)
60 break;
61
62 // Found just a parameter
63 case 2:
64 // The last parameter is still waiting.
65 // With no value, set it to true.
66 if (parameter != null)
67 {
68 if (!Parameters.Exists(p => System.String.Equals(p.Name, parameter, System.StringComparison.CurrentCultureIgnoreCase)))
69 {
70 //_parameters.Add(parameter, "true");
71 Parameters.Add(new ArgumentType(parameter, "true"));
72 }
73 }
74 parameter = parts[1];
75 break;
76
77 // Parameter with enclosed value
78 case 3:
79 // The last parameter is still waiting.
80 // With no value, set it to true.
81 if (parameter != null)
82 {
83 if (!Parameters.Exists(p => System.String.Equals(p.Name, parameter, System.StringComparison.CurrentCultureIgnoreCase)))
84 {
85 //_parameters.Add(parameter, "true");
86 Parameters.Add(new ArgumentType(parameter, "true"));
87 }
88 }
89
90 parameter = parts[1];
91
92 // Remove possible enclosing characters (",')
93 //if (!_parameters.ContainsKey(parameter))
94 if (!Parameters.Exists(p => System.String.Equals(p.Name, parameter, System.StringComparison.CurrentCultureIgnoreCase)))
95 {
96 parts[2] = remover.Replace(parts[2], "$1");
97 //_parameters.Add(parameter, parts[2]);
98 Parameters.Add(new ArgumentType(parameter, parts[2]));
99 }
100
101 parameter = null;
102 break;
103 }
104 }
105 // In case a parameter is still waiting
106 if (parameter != null)
107 {
108 //if (!_parameters.ContainsKey(parameter))
109 // _parameters.Add(parameter, "true");
110 if (!Parameters.Exists(p => System.String.Equals(p.Name, parameter, System.StringComparison.CurrentCultureIgnoreCase)))
111 {
112 Parameters.Add(new ArgumentType(parameter, "true"));
113 }
114 }
115 }
116
117 #endregion Public Constructors
118
119 #region Public Properties
120
121 public System.Collections.Generic.List<ArgumentType> Parameters
122 {
123 get { return _parameters; }
124 }
125
126 #endregion Public Properties
127
128 #region Public Indexers
129
130 // Retrieve a parameter value if it exists
131 // (overriding C# indexer property)
132 public ArgumentType this[string param]
133 {
134 get
135 {
136 ArgumentType ret = Parameters.Find(p => System.String.Equals(p.Name, param, System.StringComparison.CurrentCultureIgnoreCase));
137 if (ret == null)
138 {
139 ret = _defaultParameterNull;
140 _defaultParameterNull.Name = param;
141 _defaultParameterNull.Value = "";
142 _defaultParameterNull.Defined = false;
143 _defaultParameterNull.HasValue = false;
144 }
145 return (ret);
146 }
147 }
148
149 #endregion Public Indexers
150 }
Class ArgumentType
1
2 public class ArgumentType
3 {
4 #region Private Members
5
6 private string _name;
7 private string _value;
8
9 #endregion Private Members
10
11 #region Public Constructors
12
13 public ArgumentType()
14 {
15 Defined = false;
16 HasValue = false;
17 }
18
19 public ArgumentType(string name, string value)
20 {
21 Defined = false;
22 HasValue = false;
23 Name = name;
24 if (!string.IsNullOrWhiteSpace(value))
25 {
26 Value = value;
27 }
28 }
29
30 #endregion Public Constructors
31
32 #region Public Properties
33
34 public bool Defined
35 {
36 get; internal set;
37 }
38
39 public bool HasValue
40 {
41 get; internal set;
42 }
43
44 public string Name
45 {
46 get { return _name; }
47 set
48 {
49 _name = value;
50 Defined = true;
51 }
52 }
53
54 public string Value
55 {
56 get { return _value; }
57 set
58 {
59 _value = value;
60 HasValue = true;
61 }
62 }
63
64 public bool ValueBool
65 {
66 get {
67 try
68 {
69 return System.Convert.ToBoolean(_value);
70 }
71 catch
72 {
73 return false;
74 }
75 }
76 }
77
78 public int ValueInt
79 {
80 get
81 {
82 try
83 {
84 return System.Convert.ToInt32(_value);
85 }
86 catch
87 {
88 return 0;
89 }
90 }
91 }
92
93 #endregion Public Properties
94 }
Comments