Ini 檔案又稱設定檔,無固定格式,僅以簡單的結構與文字組成,許多程式都會將它當作初始化之檔案。
此篇文章提供程式碼中,可以將 key 和 value 寫到同一個 section,或者將某一個 section 指定 key 的 value 讀出,又或者可以將某個 section 讀出,而我參考
http://www.codeproject.com/KB/cs/cs_ini.aspx 後,寫成以下類別,方便大家引用。
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
namespace Ini
{
public class IniFile
{
public string path;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,
string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal,
int size, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileSection(string section, IntPtr lpReturnedString,
int nSize, string lpFileName);
// INIPath 為檔案路徑,isDel 為是否覆蓋原檔
public IniFile(string INIPath, bool isDel)
{
if (!isDel)
{
if (!File.Exists(INIPath))
File.Create(INIPath);
}
else
{
FileStream fs = new FileStream(INIPath, FileMode.Create);
fs.Close();
}
this.path = INIPath;
}
// 寫入指定 Section,指定 Key,指定 Value。
public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.path);
}
// 讀取指定 Section,指定 Key 的 Value。
public string IniReadValue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp,
255, this.path);
return temp.ToString();
}
// 讀取指定 Section 所有的 Value。
public string[] ReadSection(string section)
{
const int bufferSize = 2048;
StringBuilder returnedString = new StringBuilder();
IntPtr pReturnedString = Marshal.AllocCoTaskMem(bufferSize);
try
{
int bytesReturned = GetPrivateProfileSection(section, pReturnedString, bufferSize, path);
//bytesReturned -1 to remove trailing \0
for (int i = 0; i < bytesReturned - 1; i++)
returnedString.Append((char)Marshal.ReadByte(new IntPtr((uint)pReturnedString + (uint)i)));
}
finally
{
Marshal.FreeCoTaskMem(pReturnedString);
}
string sectionData = returnedString.ToString();
return sectionData.Split('\0');
}
}
}
回目錄回首頁