アプリケーションの実行ファイルのフルパス、実行ファイル名を取得する - C#
概要
アプリケーションの実行ファイルのフルパス、実行ファイル名を取得するコードを紹介します。
アプリケーションの実行ファイルのフルパスを取得するには
Application.ExecutablePath
プロパティを用います。
実行ファイル名を取得する場合は、アプリケーション実行ファイルのフルパスと、
Path.GetFileName()
メソッドを利用します。
プログラム例
Windows Formアプリケーションを作成します。
UI
フォームにボタンを1つ、テキストボックスを2つ配置します。
コード
下記コードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace GetPath
{
public partial class FormGetApplicationPath : Form
{
public FormGetApplicationPath()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string ApplicationFullPath = Application.ExecutablePath;
textBox1.Text = ApplicationFullPath;
string ApplicationFileName = Path.GetFileName(Application.ExecutablePath);
textBox2.Text = ApplicationFileName;
}
}
}
解説
アプリケーション実行ファイルのフルパスは、
Application.ExecutablePath
プロパティで取得できます。
文字列型(string)として取得できます。取得したフルパスの文字列を上部のテキストボックスに表示します。
string ApplicationFullPath = Application.ExecutablePath;
textBox1.Text = ApplicationFullPath;
アプリケーションの実行フィル名のみを取得する場合は、Pathクラスの
GetFileName()
メソッドを利用します。
与えた引数のstring型の文字列からファイル名のみをメソッドの戻り値として返します。
GetFileName メソッドの動作の詳細については
こちらの記事を参照してください。
取得できた実行ファイルのファイル名を下のテキストボックスに表示します。
string ApplicationFileName = Path.GetFileName(Application.ExecutablePath);
textBox2.Text = ApplicationFileName;
実行結果
上記のプロジェクトを実行します。下図のウィンドウが表示されます。
[button1]のボタンをクリックします。テキストボックスに値が表示されます。(下図の画面)
上部のテキストボックスにはアプリケーションの実行ファイルのフルパスが表示されます。
下部のテキストボックスにはアプリケーションの実行ファイルのファイル名のみが表示されます。
アプリケーションの実行ファイルのフルパス、実行ファイル名を取得できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2008-12-15
改訂日: 2021-07-20