記事内に広告が含まれています。

【C#】超簡単!iniファイルを読み込む方法

C#でiniファイルを読み込む方法です。超簡単です。

Win32 APIのGetPrivateProfileString関数とGetPrivateProfileInt関数を使って、iniファイルを読み込みます。

【スポンサーリンク】

iniファイルを読み込む方法

C#におけるiniファイル読み込みは、Win32 APIが必要になります。Win32 APIというのは、Windowsが提供しているAPIのことです。簡単に説明すると、自分で作ったアプリから、WindowsのOSを直接操作しますよ、ということです。

そこに用意されている、

  • GetPrivateProfileString関数
  • GetPrivateProfileInt関数

を使えば、iniファイルから値を取得できます。

【スポンサーリンク】

準備

GetPrivateProfileString関数とGetPrivateProfileInt関数を使うためには準備が必要です。

準備と言っても、OS側で何か操作が必要と言うわけではありません。ソースコードに以下を記述します。

//iniファイル読み込みに必要
using System.Runtime.InteropServices;

namespace CS_Get_Ini
{
    public partial class Form_CS_Get_Ini : Form
    {
        //---DLL関数の定義 START---//
        //GetPrivateProfileString関数の定義
        [DllImport("KERNEL32.DLL")]
        public static extern uint GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            StringBuilder lpReturnedString,
            uint nSize,
            string lpFileName);

        //GetPrivateProfileInt関数の定義
        [DllImport("KERNEL32.DLL")]
        public static extern uint GetPrivateProfileInt(
            string lpAppName,
            string lpKeyName,
            int nDefault,
            string lpFileName);
        //---DLL関数の定義 END ---//
        public Form_CS_Get_Ini()
        {
            InitializeComponent();
        }
    }
}

上記の太字にした部分が必要となります。

「[DllImport(“KERNEL32.DLL”)]」とか「extern uint」みたいな見慣れない文字が並んでいると思いますが、とりあえずiniファイルの値を取得したい方は何も考えずに、太字の部分をコピペしてみて下さい。

「using System.Runtime.InteropServices;」は、namespace の外側に記述(上でOK)、DLL関数の定義部分はクラス内に記述します(メソッド内に記述はダメ)。

というわけで、確認用に簡単な画面を作成しました。

左側はGetPrivateProfileString関数用、右側はGetPrivateProfileInt関数用です。

仕様はとても簡単で、

  1. 上のテキストボックスにiniファイルのパスを入力
  2. 実行ボタンを押下
  3. 下のテキストボックスにiniファイルから取得した値を表示

というものです。

【スポンサーリンク】

GetPrivateProfileString関数

まず、GetPrivateProfileString関数の使い方です。

GetPrivateProfileString関数はiniファイルの情報を文字列として取得します。厳密に言えば、取得する際にStringBuilder型の変数に格納されるので、文字列として扱う場合はToStringする必要があります。

実際にiniファイルを用意しました。

今回は2行目に記述している「OutPutPath」の値を取得してみます。サンプルコードはこちらです。

//iniファイル読み込みに必要
using System.Runtime.InteropServices;

namespace CS_Get_Ini
{
    public partial class Form_CS_Get_Ini : Form
    {

        // DLL関数の定義です。
        //GetPrivateProfileString関数の宣言
        [DllImport("KERNEL32.DLL")]
        public static extern uint GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            StringBuilder lpReturnedString,
            uint nSize,
            string lpFileName);

        public Form_CS_Get_Ini()
        {
            InitializeComponent();
        }

        private void cmdGetIniStr_Click(object sender, EventArgs e)
        {
            txtResultStr.Text = MyGetPrivateProfileString();
        }

        //GetPrivateProfileString関数用のメソッド
        private string MyGetPrivateProfileString()
        {
            //変数宣言
            string strSection = "LOGFILE";                          //Iniファイルのセクション
            string strKye = "OutPutPath";                           //Iniファイルのキー
            string strDefault = "Iniファイルの値がありません。";    //値が取得できなかった場合の初期値
            StringBuilder sbResult = new StringBuilder(1024);       //取得値を格納する変数
            string strFilePath = txtFilePathStr.Text;               //Iniファイルのパス

            //Iniファイル情報取得
            GetPrivateProfileString(strSection
                                    , strKye
                                    , strDefault
                                    , sbResult
                                    , Convert.ToUInt32(sbResult.Capacity)
                                    , strFilePath);

            return sbResult.ToString();
        }
    }
}

DLL定義も一緒に記述しておきました。実際に実行してみます。iniファイルのパスを入力して、実行ボタンをクリックします。

実行結果はこちら。

「OutPutPath」の値である「D:\CS\Log\」を取得できています。

サンプルコード内のコメントにも書いてますが、GetPrivateProfileString関数の引数は次のようになっています。

  • 第1引数:セクション名 … [] で囲まれている部分
  • 第2引数:キー名 … イコール(=)の左側
  • 第3引数:初期値 … iniファイルから値が取得できなかった場合の値
  • 第4引数:許容範囲 … とりあえず「Convert.ToUInt32(StringBuilderの変数名.Capacity)」って書いておけばOK
  • 第5引数:iniファイルのフルパス

これらの引数を、ご自身の環境に合わせて記述して、実行してみて下さい。

【スポンサーリンク】

GetPrivateProfileInt関数

次に、GetPrivateProfileInt関数の使い方です。

GetPrivateProfileInt関数はiniファイルの情報を数値として取得します。取得後にキャストする必要があるので、少し工夫します。

実際にiniファイルを用意しました。

今回は7行目に記述している「ValueNum」の値を取得してみます。サンプルコードはこちらです。

//iniファイル読み込みに必要
using System.Runtime.InteropServices;

namespace CS_Get_Ini
{
    public partial class Form_CS_Get_Ini : Form
    {
        //GetPrivateProfileInt関数の宣言
        [DllImport("KERNEL32.DLL")]
        public static extern uint GetPrivateProfileInt(
            string lpAppName,
            string lpKeyName,
            int nDefault,
            string lpFileName);

        public Form_CS_Get_Ini()
        {
            InitializeComponent();
        }

        private void cmdGetIniInt_Click(object sender, EventArgs e)
        {
            txtResultInt.Text = MyGetPrivateProfileInt().ToString();    //【注意】テキストボックスに表示するためにToStringしている。
        }

        //GetPrivateProfileInt関数用のメソッド
        private int MyGetPrivateProfileInt()
        {
            //変数宣言
            string strSection = "VALUE";                    //Iniファイルのセクション
            string strKye = "ValueNum";                     //Iniファイルのキー
            int intDefault = 0;                             //値が取得できなかった場合の初期値
            string strFilePath = txtFilePathInt.Text;       //Iniファイルのパス
            int intRet;                                     //このメソッドの戻り値用

            //キャストして変数に格納
            intRet=(int)GetPrivateProfileInt(strSection
                                            , strKye
                                            , intDefault
                                            , strFilePath);

            return intRet;
        }
    }
}

これを実際に実行してみましょう。iniファイルのパスを入力して、実行ボタンをクリックします。

実行結果はこちら。

「ValueNum」の値である「1000」を取得できています。

サンプルコード内のコメントにも書いてますが、GetPrivateProfileInt関数の引数は次のようになっています。

  • 第1引数:セクション名 … [] で囲まれている部分
  • 第2引数:キー名 … イコール(=)の右側
  • 第3引数:初期値 … iniファイルから値が取得できなかった場合の値
  • 第4引数:iniファイルのパス

ここで肝なのが、GetPrivateProfileInt関数を実際に実行する部分。サンプルコード上では次の様に記載しています。

//キャストして変数に格納
intRet=(int)GetPrivateProfileInt(strSection
                                , strKye
                                , intDefault
                                , strFilePath);

可視化のため、明示的に戻り値用のint型変数 intRet を用意しています。

戻り値用の intRet にGetPrivateProfileInt関数の戻り値をそのまま代入するコードを書くとコンパイルエラーとなるので、GetPrivateProfileInt関数の戻り値をint型でキャストしてあげて下さい。

【スポンサーリンク】

参考サイト

API インデックス – Win32 apps | Microsoft Docs

DllImportAttribute クラス (System.Runtime.InteropServices) | Microsoft Docs

【スポンサーリンク】

鉄道記事も書いてます!

ちょっとリフレッシュして鉄道記事も読んでみませんか?

鉄道記事バックナンバーはこちら↓

鉄道コム投稿記事一覧ページ