実行時のファイルパスやコマンドライン引数を取得する
About
実行時にコマンドライン引数を指定することで、アプリケーションの挙動を制御したい場合があります。WPFアプリケーションでも実装することができるので、ここではその方法について解説します。
WpfApplication_GetCommandLineArgs.zip
- VisualStudio2012
- .Netframework4.5
HowTo
一般的な取得方法
ディレクトリであれば、AppDomain.CurrentDomain.BaseDirectoryで取得することができます。
string directory = System.AppDomain.CurrentDomain.BaseDirectory;
一般的な取得方法はEnvironment.GetCommandLineArgsを利用する方法であると思われます。引数の先頭は常に実行時の(実行ファイルの)パスになるので、パスを取得する目的でも利用することができます。
string path = Environment.GetCommandLineArgs()[0];
実行直後に取得する
普通に開発している分には、あまり馴染みのない"App.xaml"とそのコード"App(.xaml).xs"でコマンドライン引数を取得することができます。Appクラスは、"Startupイベント"を通知します。このイベントハンドラ内でコマンドライン引数を取得します。
App.xamlにStartupイベントを追加するコードは次の通りです。
<Application x:Class="WpfApplication_GetCommandLineArgs.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml" Startup="Application_Startup"> <Application.Resources> </Application.Resources> </Application>
XAMLに定義したイベントハンドラの実体はコード(App.xaml.cs)に実装することになります。コマンドライン引数は、StartupEventArgsのArgsプロパティから取得することができます。
/// <summary> /// App.xaml の相互作用ロジック /// </summary> public partial class App : Application { private void Application_Startup(object sender, StartupEventArgs e) { string[] args = e.Args; foreach(string temp in args) Console.WriteLine(temp); } }