■ サンプル
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace SampleForm
{
public partial class Form1 : Form
{
private const string IniFilePath = @"c:\hello-world.ini";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// キーと値を書き加える
WritePrivateProfileString(
"Section1", "Key1", "Hello", IniFilePath);
WritePrivateProfileString(
"Section1", "Key2", "1234", IniFilePath);
WritePrivateProfileString(
"Section2", "Key1", "World", IniFilePath);
// 文字列を読み出す
var stringBuilder = new StringBuilder(1024);
GetPrivateProfileString("Section1", "Key1", "default", stringBuilder,
(uint)stringBuilder.Capacity, IniFilePath);
Console.WriteLine("Key : {0}", stringBuilder.ToString());
// 整数値を読み出す
var resultValue = GetPrivateProfileInt("Section1", "Key2", 0, IniFilePath);
Console.WriteLine("Section : {0}", resultValue);
// 指定セクションのキーの一覧を得る
var resultArray = new byte[1024];
var resultArraySize = GetPrivateProfileStringByByteArray(
"Section1", null, "default", resultArray, (uint)resultArray.Length, IniFilePath);
var result = Encoding.Default.GetString(resultArray, 0, (int)resultArraySize - 1);
var keys = result.Split('\0');
foreach (string key in keys)
{
Console.WriteLine("Key : {0}", key);
}
// 指定ファイルのセクションの一覧を得る
var resultArray2 = new byte[1024];
var resultSize2 = GetPrivateProfileStringByByteArray(
null, null, "default", resultArray2, (uint)resultArray2.Length, IniFilePath);
string result2 = Encoding.Default.GetString(resultArray2, 0, (int)resultSize2 - 1);
string[] sections = result2.Split('\0');
foreach (string section in sections)
{
Console.WriteLine("Section : {0}", section);
}
// 1つのキーと値のペアを削除する
WritePrivateProfileString("Section2", "Key1", null, IniFilePath);
// 指定セクション内の全てのキーと値のペアを削除する
WritePrivateProfileString("Section1", null, null, IniFilePath);
this.label1.Text = "Done!";
}
[DllImport("KERNEL32.DLL")]
public static extern uint
GetPrivateProfileString(
string lpAppName,
string lpKeyName,
string lpDefault,
StringBuilder lpReturnedString,
uint nSize,
string lpFileName);
[DllImport("KERNEL32.DLL",
EntryPoint = "GetPrivateProfileStringA")]
public static extern uint
GetPrivateProfileStringByByteArray(
string lpAppName,
string lpKeyName,
string lpDefault,
byte[] lpReturnedString,
uint nSize,
string lpFileName);
[DllImport("KERNEL32.DLL")]
public static extern uint
GetPrivateProfileInt(
string lpAppName,
string lpKeyName,
int nDefault,
string lpFileName);
[DllImport("KERNEL32.DLL")]
public static extern uint WritePrivateProfileString(
string lpAppName,
string lpKeyName,
string lpString,
string lpFileName);
}
}
出力結果
Key : Hello
Section : 1234
Key : Key1
Key : Key2
Section : Section2
Section : Section1
hello-world.ini
[Section2]