前回は、C#でiniファイルに記述されたセクション名の一覧を取得してみた。
せっかくなのでその情報も取得してみよう。まず、対象となるiniファイルを再掲する。
test.ini
[Bob]
Age=17
[John]
Age=6
[Mike]
Age=31
[Ken]
Age=35
[Alice]
Age=4
Age=17
[John]
Age=6
[Mike]
Age=31
[Ken]
Age=35
[Alice]
Age=4
今回はAgeの部分を取得したい。そのためにはWindowsAPIのGetPrivateProfileString()関数を使う必要がある。
C#から呼び出すためのPInvoke宣言は以下のようになる。
[DllImport("kernel32.dll")] static extern uint GetPrivateProfileString( string lpAppName, // セクション名 string lpKeyName, // キー名 string lpDefault, // 規定の文字列 StringBuilder lpReturnedString, // 情報が格納されるバッファ uint nSize, // 情報バッファのサイズ string lpFileName // .iniファイルの名前 );
そして、プログラム全体は以下のようになった。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using System.IO; namespace PInvokeLesson { public partial class Form1 : Form { [DllImport("kernel32.dll")] static extern int GetPrivateProfileSectionNames( IntPtr lpszReturnBuffer, uint nSize, string lpFileName); [DllImport("kernel32.dll")] static extern uint GetPrivateProfileString( string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName); public Form1() { InitializeComponent(); } // Windowsフォーム アプリケーション // プロジェクト初期状態のフォームにボタンを一つ追加し、 // そのクリックイベントハンドラからプログラムは開始する。 private void button1_Click(object sender, EventArgs e) { String path = Application.StartupPath + Path.DirectorySeparatorChar + "test.ini"; if (File.Exists(path)) { IntPtr ptr = Marshal.StringToHGlobalAnsi(new String('\0', 1024)); int length = GetPrivateProfileSectionNames(ptr, 1024, path); if (0 < length) { String result = Marshal.PtrToStringAnsi(ptr, length).TrimEnd(new char[] { '\0' }); Array.ForEach<String>(result.Split('\0'), s => { StringBuilder sb = new StringBuilder(64); // iniファイルから情報を取得する GetPrivateProfileString(s, "Age", "", sb, 64, path); // 取得した情報を表示 Console.WriteLine("Name:" + s + " Age:" + sb.ToString() ); }); } Marshal.FreeHGlobal(ptr); } } } }
プログラムの実行フォルダに、test.iniファイルがあることを確認し
実行すると以下のように表示される。
Name:Bob Age:17
Name:John Age:6
Name:Mike Age:31
Name:Ken Age:35
Name:Alice Age:4