1.前言
利用Windows API來讀取標準的ini檔案。

2.說明
ini檔案的格式可以參考wiki的說明
http://en.wikipedia.org/wiki/INI_file

程式碼:

[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool WritePrivateProfileString(string sectionName, string keyName, string keyValue, string filePath);

[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetPrivateProfileString(string sectionName, string keyName, string defaultReturnString, StringBuilder returnString, int returnStringLength, string filePath);

3.應用

//建立ini檔案
WritePrivateProfileString("Owner", "name", "Dan Mac", @"D:\Temp\myConfig.ini");
WritePrivateProfileString("Owner", "organization", "Apple Inc.", @"D:\Temp\myConfig.ini");
WritePrivateProfileString("Database", "server", "192.168.1.100", @"D:\Temp\myConfig.ini");
WritePrivateProfileString("Database", "port", "50000", @"D:\Temp\myConfig.ini");
WritePrivateProfileString("Database", "file", "\"db.dat\"", @"D:\Temp\myConfig.ini");
//myConfig.ini檔案內容
[Owner]
name=Dan Mac
organization=Apple Inc.
[Database]
server=192.168.1.100
port=50000
file="db.dat"
//讀取ini檔案
StringBuilder data = new StringBuilder(255);
GetPrivateProfileString("Database", "file", "NA", data, 255, @"D:\Temp\myConfig.ini");
Console.WriteLine(data);

    文章標籤

    C# Windows API ini

    全站熱搜

    西夏普 發表在 痞客邦 留言(0) 人氣()