忍者ブログ

VB.NET-TIPS などプログラミングについて

VB.NETのTIPS(小技集)を中心に、Javascript、PHP その他のプログラミングについて少し役に立つ情報を発信します。いわゆる個人的な忘備録ですが、みなさんのお役に立てれば幸いです。

EXEの実行ファイル(フォルダ)を取得する

EXEファイルの実行フォルダが必要になることはよくあります。 フォルダを取得して、そこからの相対フォルダ参照で、データフォルダなどを作成・参照を行ったりしますので、 その方法について示します。

まず最初は通常のWindowsフォームを持っているEXEファイルに付いてです。

WindowsフォームでのEXEファイル取得

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim strPath As String = ""

    'System.Windows.Forms.Application のSharedプロパティ「ExecutablePath」を参照
    ' アプリケーションを開始した実行可能ファイルのパスを、ファイル名を含めて取得します。
    strPath = System.Windows.Forms.Application.ExecutablePath
    Console.WriteLine("ExecutablePathdでのExeフルパス:[{0}]", strPath)

    '因みに、System.Windows.Forms.Application のSharedプロパティ「StartupPath」を参照
    ' アプリケーションを開始した実行可能ファイルのファイル名を含まないパス取得します。
    strPath = System.Windows.Forms.Application.StartupPath
    Console.WriteLine("StartupPathでのExeフルパス:[{0}]", strPath)
End Sub

実行結果は以下の様になります。

ExecutablePathdでのExeフルパス:[C:¥TestSrv¥BlogTest¥BlogTest¥bin¥Debug¥BlogTest.EXE]
StartupPathでのExeフルパス:[C:¥TestSrv¥BlogTest¥BlogTest¥bin¥Debug]

コンソールアプリの場合にはこれは使えないので、以下の様に自分自身のアセンブリを取得し、そのLocationプロパティ を取得することでEXEのフルパスが取得できます。

GetExecutingAssembly().Location でのEXEファイル取得

Module MdlMainPath
    'Main関数
    Sub Main()
        Dim strPath As String = ""
        'GetExecutingAssembly().Locationでの実行ファイルのパスを取得する
        strPath = System.Reflection.Assembly.GetExecutingAssembly().Location
        Console.WriteLine("GetExecutingAssembly().LocationでのExeフルパス:[{0}]", strPath)

        'パスから実行フォルダのみを取り出す
        strPath = System.IO.Path.GetDirectoryName(strPath)
        Console.WriteLine("GetExecutingAssembly().LocationでのExeフォルダ:[{0}]", strPath)
    End Sub
End Module

実行結果は以下の様になります。

GetExecutingAssembly().LocationでのExeフルパス:[C:¥TestSrv¥BlogTest¥BlogTest¥bin¥Debug¥BlogTest.exe]
GetExecutingAssembly().LocationでのExeフォルダ:[C:¥TestSrv¥BlogTest¥BlogTest¥bin¥Debug]

関連する記事

フォルダコピー(サブフォルダ以下も含む):[Directory.GetFiles,Directory.GetDirectories]
指定フォルダ内の全ファイルを削除   :[Directory.GetFiles,File.Delete]
指定フォルダ内の全ファイルをクリア  :[Directory.GetFiles,File.Delete]












PR

コメント

コメントを書く