LoginSignup
1
0

More than 5 years have passed since last update.

Visual Studio | WPF > fileIO > アプリケーションのパスを得る > GetExecutingAssembly().Location | MainModule.FileName など

Last updated at Posted at 2017-12-25
動作環境
Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2

WPFでアプリケーション(実行ファイル)のパスを取得したい。

参考

code

以下の3種類は使えることはわかった。

MainWindow.xaml.cs
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プロパティを取得する分には問題はないのかもしれない。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0