Ini配置文件可以使用读写文本的方法处理,也可以使用API进行操作。
Ini配置文件的格式如下:
[主键名]
子键名1 = 键值1
子键名2 = 键值2
子键名3 = 键值3
……………………
子键名n = 键值n
Kernel32.dll中提供了GetPrivateProfileString和WritePrivateProfileString两个方法进行Ini文件的读写操作:
[ DllImport (
"
kernel32
"
) ]
private
static
extern
int
GetPrivateProfileString (
string
section ,
string
key ,
string
def , System.Text.StringBuilder retVal ,
int
size ,
string
filePath ) ;
//
读取键值
public
static
string
ReadIni(
string
主键名,
string
子键名,
string
默认键值,
int
数值大小,
string
文件路径)
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
string m_ret=默认键值;
try
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
System.Text.StringBuilder 返回值=new System.Text.StringBuilder(默认键值);
GetPrivateProfileString(主键名,子键名,默认键值,返回值,数值大小,文件路径);
m_ret=返回值.ToString();
}
catch
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
m_ret=默认键值;
}
return m_ret;
}
[ DllImport (
"
kernel32
"
) ]
private
static
extern
long
WritePrivateProfileString (
string
section ,
string
key ,
string
val ,
string
filePath ) ;
//
写入键值
public
static
bool
WriteIni(
string
主键名,
string
子键名,
string
数值,
string
文件路径)
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
bool m_ret=true;
try
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
WritePrivateProfileString(主键名,子键名,数值,文件路径);
}
catch
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
m_ret=false;
}
return m_ret;
}