Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2
WPFでアプリケーション(実行ファイル)のパスを取得したい。
参考
- https://stackoverflow.com/questions/3123870/find-the-location-of-my-applications-executable-in-wpf-c-or-vb-net
- Windows GUIプログラミング入門11 設定保存(2)
code
以下の3種類は使えることはわかった。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace _171225_t0955_appFilepath
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void B_apppath_Click(object sender, RoutedEventArgs e)
{
string appPath1 = System.Reflection.Assembly.GetExecutingAssembly().Location;
string appPath2 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
string appPath3 = System.Reflection.Assembly.GetEntryAssembly().Location;
//MessageBox.Show(appPath1);
}
}
}
どれも今日の晩には忘れていそうな記述ばかり。
MainModule.FileName
だけ覚えておくと見つかりやすいだろうか。
appPath1のはまり
appPath1 については上記のStackoverflowのコメントに下記がある。
This may not work properly all the times. It will get the executing assembly, not the application's executable. ...
appPath2のはまり
appPath2については以下の「はまり」事項があるようだ。
64bit環境で、Process.GetProcesses()を使用しウィンドウをもつプロセスのMainModule.FileNameを取得したい。 by Icoさん
しかし、これを64bit環境で実行すると、
p.MainModuleにアクセスした時点で32 ビット プロセスは、64 ビット プロセスのモジュールにアクセスできません。
とエラーが出る。
それに関する解決案は以下にある。
https://stackoverflow.com/questions/9501771/how-to-avoid-a-win32-exception-when-accessing-process-mainmodule-filename-in-c
プロセスの権限が関係しそう。自分自身のプロセスのMainModuleプロパティを取得する分には問題はないのかもしれない。