读书人

读写配备config文件

发布时间: 2012-11-18 10:51:21 作者: rapoo

读写配置config文件


一、配置文件的内容如下:

[UserInfo]
Id=1001
Name=de

二、读取配置文件的代码如下

1)首先应用其命名空间using System.Runtime.InteropServices; 为了引用其DLLimport

2)读取的封装方法

  [DllImport("kernel32")]        //kernel32导入这个文件,操作ini就靠它了        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);        public string IniReadValue(string Section, string Key, string inipath)        {            StringBuilder temp = new StringBuilder(500);            GetPrivateProfileString(Section, Key, "", temp, 500, inipath);            return temp.ToString();        }


3)测试用例如下

   string section = "UserInfo";//配置段            string key = "Id";//键            string inipath = "C:\\config";//配置文件路径            string value = IniReadValue(section, key, inipath);//获取value输出到tb_value中            MessageBox.Show(value);


4)修改配置文件的封装方法

  [DllImport("kernel32")]        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);        public void IniWriteValue(string Section, string Key, string Value, string inipath)        {            WritePrivateProfileString(Section, Key, Value, inipath);        }


5)测试用例如下;

    string section = "UserInfo";//配置段            string key = "Name";//键            string inipath = "C:\\config";//配置文件路径            string value = "de";            IniWriteValue(section, key, value, inipath);


读书人网 >编程

热点推荐