Ini配置文件可以使用读写文本的方法处理,也可以使用API进行操作。

Ini配置文件的格式如下:

[主键名]
子键名1 = 键值1
子键名2 = 键值2
子键名3 = 键值3
……………………
子键名n = 键值n


Kernel32.dll中提供了GetPrivateProfileString和WritePrivateProfileString两个方法进行Ini文件的读写操作:


用API读写INI配置文件        [ DllImport ( "kernel32" ) ]
用API读写INI配置文件        
private static extern int GetPrivateProfileString ( string section ,string key , string def , System.Text.StringBuilder retVal ,int size , string filePath ) ;
用API读写INI配置文件

用API读写INI配置文件        //读取键值
用API读写INI配置文件
        public static string ReadIni(string 主键名,string 子键名,string 默认键值,int 数值大小,string 文件路径)                        
{
用API读写INI配置文件            
string m_ret=默认键值;
用API读写INI配置文件            
try
{
用API读写INI配置文件        
用API读写INI配置文件                System.Text.StringBuilder 返回值
=new System.Text.StringBuilder(默认键值);
用API读写INI配置文件                GetPrivateProfileString(主键名,子键名,默认键值,返回值,数值大小,文件路径);
用API读写INI配置文件                m_ret
=返回值.ToString();
用API读写INI配置文件            }

用API读写INI配置文件            
catch
{
用API读写INI配置文件                m_ret
=默认键值;
用API读写INI配置文件            }

用API读写INI配置文件            
return m_ret;
用API读写INI配置文件        }



用API读写INI配置文件        [ DllImport ( "kernel32" ) ]
用API读写INI配置文件        
private static extern long WritePrivateProfileString ( string section ,    string key , string val , string filePath ) ;
用API读写INI配置文件

用API读写INI配置文件        //写入键值
用API读写INI配置文件
        public static bool WriteIni(string 主键名,string 子键名,string 数值,string 文件路径)                                        
{
用API读写INI配置文件            
bool m_ret=true;
用API读写INI配置文件            
try
{
用API读写INI配置文件                WritePrivateProfileString(主键名,子键名,数值,文件路径);
用API读写INI配置文件            }

用API读写INI配置文件            
catch
{
用API读写INI配置文件                m_ret
=false;
用API读写INI配置文件            }

用API读写INI配置文件            
return m_ret;
用API读写INI配置文件            
用API读写INI配置文件        
用API读写INI配置文件        
用API读写INI配置文件        }


用API读写INI配置文件

相关文章: