【C#】実行ファイルと同じ場所にある設定ファイルのパスを取得する

C#

小規模アプリの場合、実行ファイル(exe)と同じ場所に設定ファイルを格納することは、よくある実装だと思います。この記事では、実行ファイルと同じ場所にある設定ファイルのパスを生成する処理のサンプルを紹介します。

サンプル1:実行ファイルと同じファイル名の拡張子違い

Application.exeに対応する設定ファイルがApplication.iniの場合、実行中のアプリケーションのフルパスを取得し、Path.ChangeExtensionで拡張子を変更すれば、設定ファイルのフルパスを取得できます。

using System;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 実行中のアプリケーションのフルパスを取得
            string appFullPath = Application.ExecutablePath;

            // アプリケーションと同じ名前を持つ設定ファイルのパスを取得
            string configFilePath = Path.ChangeExtension(appFullPath, ".ini");

            // 設定ファイルのパスを表示
            MessageBox.Show("設定ファイルのパス: " + configFilePath);
        }
    }
}

サンプル2:実行ファイルとは異なるファイル名

Application.exeに対応する設定ファイルがconfig.iniの場合、実行中のアプリケーション格納ディレクトリのフルパスと設定ファイル名config.iniを結合すれば、設定ファイルのフルパスを取得できます。

using System;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 実行中のアプリケーションのフルパスを取得
            string appFullPath = Application.ExecutablePath;

            // アプリケーションのディレクトリパスを取得
            string dirPath = Path.GetDirectoryName(appFullPath);

            // ディレクトリパスを取得と設定ファイル名を結合する
            string configFilePath = Path.Combine(dirPath, "config.ini");

            // 設定ファイルのパスを表示
            MessageBox.Show("設定ファイルのパス: " + configFilePath);
        }
    }
}

まとめ

この記事では、実行ファイルと同じ場所にある設定ファイルのパスを生成する処理のサンプルを紹介しました。

タイトルとURLをコピーしました