C#读写.ini文件

来源:互联网 发布:腾讯体育nba数据库 编辑:程序博客网 时间:2024/05/16 11:09

C#中对Win32的API函数的互操作是通过命名空间“System.Runtime.InteropServices”中的“DllImport”特征类来实现的。它的主要作用是指示此属性化方法是作为非托管DLL的输出实现的。下面代码就是在C#利用命名空间“System.Runtime.InteropServices”中的“DllImport”特征类申明Win32的API函数:
C#申明INI文件的写操作函数WritePrivateProfileString():
[ DllImport ( "kernel32" ) ]
private static extern long WritePrivateProfileString ( string section ,string key , string val , string filePath ) ;
参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。

在指定的路径下创建INI文件,当INI文件不存在时WritePrivateProfileString()实现的是创建功能;当INI文件存在时WritePrivateProfileString()实现的是信息追加功能。
C#申明INI文件的读操作函数GetPrivateProfileString():
[ DllImport ( "kernel32" ) ]
private static extern int GetPrivateProfileString ( string section ,string key , string def , StringBuilder retVal ,int size , string filePath ) ;
参数说明:section:INI文件中的段落名称;key:INI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;filePath:INI文件的完整路径和名称。

对INI文件进行写操作,是通过组件button2的"Click"事件来实现的。这里有一点应该注意,当在调用WritePrivateProfileString()对INI文件进行写操作的时候,如果此时在INI文件中存在和要写入的信息相同的段落名称和关键字,则将覆盖此INI信息。下面是button2组件的"Click"事件对应的代码清单:
string FileName = textBox1.Text ;
string section = textBox2.Text ;
string key = textBox3.Text
string keyValue = textBox4.Text ;
WritePrivateProfileString ( section , key , keyValue , FileName ) ;
MessageBox.Show ( "成功写入INI文件!" , "信息" ) ;
C#对INI文件进行读操作:
正确读取INI的必须满足三个前提:INI文件的全路径、段落名称和关键字名称。否则就无法正确读取。你可以设定读取不成功后的缺省数值,在下面的程序中,为了直观设定的是“无法读取对应数值!”字符串,下面是其对应的代码清单:
StringBuilder temp = new StringBuilder ( 255 ) ;
string FileName = textBox1.Text ;
string section = textBox2.Text ;
string key = textBox3.Text ;
int i = GetPrivateProfileString ( section , key ,"无法读取对应数值!",
temp , 255 , FileName ) ;
//显示读取的数值
textBox4.Text = temp.ToString ( ) ;

原创粉丝点击