栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

C# ini配置文件的读取及写入

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C# ini配置文件的读取及写入

工作中一直比较少用ini配置文件,就算用到也基本手撸代码来处理,最近在一个小项目中使用的是因时间紧急又一下找不到以前手撸的代码放哪了,就上网找了一下发现原来windows自带的kernel32库中就已打包ini配置文件的操作,简单易用。

比如我们手上有一个ini文件内容如下:

[zhangsan]    
country=china
age=100

[peter]
country=JPA
age=50

我们对ini操作的工具类代码如下

 public class iniUtil
    {
        private const int VALUE_MAX_LEN = 1024;

        /// 
        /// 获取值
        /// 
        /// 段落名
        /// 键名
        /// 读取异常是的缺省值
        /// 键名所对应的的值,没有找到返回空值
        /// 返回值允许的大小
        /// ini文件的完整路径
        /// 
        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileString(
            string section,
            string keyName,
            string defaultValue,
            StringBuilder returnValue,
            int size,
            string filepath);

        /// 
        /// 写入
        /// 
        /// 需要写入的段落名
        /// 需要写入的键名
        /// 写入值
        /// ini文件的完整路径
        /// 
        [DllImport("kernel32.dll")]
        private static extern int WritePrivateProfileString(
            string section,
            string key,
            string val,
            string filepath);


        /// 
        /// 外部函数:读配置
        /// 
        /// 文件名
        /// 段落名
        /// 键名
        /// 默认值
        /// 
        public static string ReadProfileValue(string filename, string section, string keyName, string defaultValue)
        {
            StringBuilder returnValue = new StringBuilder(VALUE_MAX_LEN + 1);
            GetPrivateProfileString(section, keyName, defaultValue, returnValue, VALUE_MAX_LEN, filename);
            return returnValue.ToString();
        }
     
		/// 
        /// 外部函数:写配置
        /// 
        /// 文件名
        /// 段落名
        /// 键名
        /// 默认值
        /// 
        public static bool WriteProfileValue(string filename, string section, string keyName, string keyValue)
        {
            return (0 != WritePrivateProfileString(section, keyName, keyValue, filename));
        }

    }

比如我们读上方实例ini文件中zhangsan段落的country内容代码如下:

iniUtil util = new iniUtil();
var country = util.ReadProfileValue(@"C:Testtest.ini",	//文件路径
                     "zhangsan",	//对应ini文件的[zhangsan]
                     "country",		//对应[zhangsan]下的country
                     "CHN");		//如果文件中没有该项的时候返回的默认值

我们现在写入一个叫 SysEnv 段落并配置IP和Port的内容代码如下:

iniUtil util = new iniUtil();
util.WriteProfileValue(@"C:Testtest.ini",	
								 "SysEnv ",	
                     			 "IP",		
                     			 "127.0.0.1");		

util.WriteProfileValue(@"C:Testtest.ini",	
								 "SysEnv ",	
                     			 "Port",		
                     			 "10086");		

这简单的工具类代码如下,使用的再根据自身情况把它做成Static方法或做成全局变量

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946398.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号