代码如下:
///<summary>
///读写INI文件的类。
///</summary>
publicclassINIHelper
{
//读写INI文件相关。
[DllImport(“kernel32.dll”,EntryPoint=”WritePrivateProfileString”,CharSet=CharSet.Ansi)]
publicstaticexternlongWritePrivateProfileString(stringsection,stringkey,stringval,stringfilePath);
[DllImport(“kernel32.dll”,EntryPoint=”GetPrivateProfileString”,CharSet=CharSet.Ansi)]
publicstaticexternintGetPrivateProfileString(stringsection,stringkey,stringdef,StringBuilderretVal,intsize,stringfilePath);
[DllImport(“kernel32.dll”,EntryPoint=”GetPrivateProfileSectionNames”,CharSet=CharSet.Ansi)]
publicstaticexternintGetPrivateProfileSectionNames(IntPtrlpszReturnBuffer,intnSize,stringfilePath);
[DllImport(“KERNEL32.DLL”,EntryPoint=”GetPrivateProfileSection”,CharSet=CharSet.Ansi)]
publicstaticexternintGetPrivateProfileSection(stringlpAppName,byte[]lpReturnedString,intnSize,stringfilePath);
///<summary>
///向INI写入数据。
///</summary>
///<PARAMname=”Section”>节点名。</PARAM>
///<PARAMname=”Key”>键名。</PARAM>
///<PARAMname=”Value”>值名。</PARAM>
publicstaticvoidWrite(stringSection,stringKey,stringValue,stringpath)
{
WritePrivateProfileString(Section,Key,Value,path);
}
///<summary>
///读取INI数据。
///</summary>
///<PARAMname=”Section”>节点名。</PARAM>
///<PARAMname=”Key”>键名。</PARAM>
///<PARAMname=”Path”>值名。</PARAM>
///<returns>相应的值。</returns>
publicstaticstringRead(stringSection,stringKey,stringpath)
{
StringBuildertemp=newStringBuilder(255);
inti=GetPrivateProfileString(Section,Key,””,temp,255,path);
returntemp.ToString();
}
///<summary>
///读取一个ini里面所有的节
///</summary>
///<paramname=”sections”></param>
///<paramname=”path”></param>
///<returns></returns>
publicstaticintGetAllSectionNames(outstring[]sections,stringpath)
{
intMAX_BUFFER=32767;
IntPtrpReturnedString=Marshal.AllocCoTaskMem(MAX_BUFFER);
intbytesReturned=GetPrivateProfileSectionNames(pReturnedString,MAX_BUFFER,path);
if(bytesReturned==0)
{
sections=null;
return-1;
}
stringlocal=Marshal.PtrToStringAnsi(pReturnedString,(int)bytesReturned).ToString();
Marshal.FreeCoTaskMem(pReturnedString);
//useofSubstringbelowremovesterminatingnullforsplit
sections=local.Substring(0,local.Length-1).Split(‘