C#中读写INI配置文件的方法
程序员文章站
2023-12-17 19:49:28
在作应用系统开发时,管理配置是必不可少的。例如数据库服务器的配置、安装和更新配置等等。由于xml的兴起,现在的配置文件大都是以xml文档来存储。比如visual studi...
在作应用系统开发时,管理配置是必不可少的。例如数据库服务器的配置、安装和更新配置等等。由于xml的兴起,现在的配置文件大都是以xml文档来存储。比如visual studio.net自身的配置文件mashine.config,asp.net的配置文件web.config,包括我在介绍remoting中提到的配置文件,都是xml的格式。
传统的配置文件ini已有被xml文件逐步代替的趋势,但对于简单的配置,ini文件还是有用武之地的。ini文件其实就是一个文本文件,它有固定的格式,节section的名字用[]括起来,然后换行说明key的值:
[section]
key=value
如数据库服务器配置文件:
dbserver.ini
[server] name=localhost [db] name=northwind [user] name=sa
在c#中,对配置文件的读写是通过api函数来完成的,代码很简单:
using system; using system.text; using system.io; using system.runtime.interopservices; namespace pubop { public class operateinifile { #region api函数声明 [dllimport("kernel32")]//返回0表示失败,非0为成功 private static extern long writeprivateprofilestring(string section,string key, string val,string filepath); [dllimport("kernel32")]//返回取得字符串缓冲区的长度 private static extern long getprivateprofilestring(string section,string key, string def,stringbuilder retval,int size,string filepath); #endregion #region 读ini文件 public static string readinidata(string section,string key,string notext,string inifilepath) { if(file.exists(inifilepath)) { stringbuilder temp = new stringbuilder(1024); getprivateprofilestring(section,key,notext,temp,1024,inifilepath); return temp.tostring(); } else { return string.empty; } } #endregion #region 写ini文件 public static bool writeinidata(string section,string key,string value,string inifilepath) { if(file.exists(inifilepath)) { long opstation = writeprivateprofilestring(section,key,value,inifilepath); if(opstation == 0) { return false; } else { return true; } } else { return false; } } #endregion } }
简单说明以下方法writeinidata()和readinidata()的参数。
section参数、key参数和inifilepath不用再说,value参数表明key的值,而这里的notext对应api函数的def参数,它的值由用户指定,是当在配置文件中没有找到具体的value时,就用notext的值来代替。
notext 可以为null或""
总结
以上所述是小编给大家介绍的c#中读写ini配置文件的方法,希望对大家有所帮助