C#で作ったExeファイルにコマンドラインオプションを与えるときに調べたときのメモ。
hoge.exe -hoge XXX -hogehoge YYY などをDictionaryで取得したいなーと思って調べてた。
参考にしたのはこちら。正直副作用はよくわかってないかも…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//argsに起動時の引数が入ってると仮定 //対応するオプションを指定 var argOptions = new HashSet {"-foo", "-bar"}; string argKey = null; Dictionary<string, string> argResult = new Dictionary<string, string>(); try { argResult = args.GroupBy(s => argOptions.Contains(s) ? argKey = s : argKey).ToDictionary(g => g.Key, g => g.Skip(1).FirstOrDefault()); } catch(System.Exception e) { //エラー処理が必要なら } if (argResult.ContainsKey("-foo") == true) { //-fooの後に値を指定するタイプのオプションなら string tmpValue = argResult["-foo"]; } else { //オプションが指定されていないときのデフォルト処理とか } |
スポンサーリンク