当前位置: 移动技术网 > IT编程>开发语言>c# > c#读写ini配置文件示例

c#读写ini配置文件示例

2019年07月18日  | 移动技术网IT编程  | 我要评论

其他人写的都是调用非托管kernel32.dll。我也用过 但是感觉兼容性有点不好 有时候会出现编码错误,毕竟一个是以前的系统一个是现在的系统。咱来写一个纯c#的ini格式配置文件读取,其实就是文本文件读写啦。但是我们要做的绝不仅仅是这样 是为了访问操作的方便 更是为了以后的使用。


都知道ini格式的配置文件里各个配置项 其实就是一行一行的文本 key跟value 用等号隔开。
像这样:
grade=5 。
各个配置项又进行分组 同类型的放到一起 称之为section 以中括号([])区分。
像这样:
[contact]
qq=410910748
website=assassinx.cnblogs.com
[score]
math=85
chinese=90
geographic=60
各个配置项的key在section内不可重复。

在这里我们为了方便 去掉section的概念 ,实际上也用不怎么到。那么这样一来就可以把个个配置项理解成一个dictionary结构,方便我们存取等操作 。至于为什么一定要使用dictionary 因为在测试时我发现存取过程中他不会打乱元素的存放顺序 晕 就这样啊。 我们要做到就是根据key去取value。还有就是需要注意到我们有时候需要在配置文件里写注释怎么办呢?就是以分号(;)开头的行。这个问题我们可以在程序里为他初始化特殊的key+序号的形式 ,写入的时候也同样的进行判断。

这整个过程就是:
程序开始时遍历所有行 如果以分号(;)开头则存储此行不作为配置解释,如果不是 则解释此行 并放到dictionary集合里去。访问时 根据key获取value 就这么简单。注意注释行的处理  还有更改配置存回去行的先后顺序必须保持原样。

好了开工吧:

复制代码 代码如下:

public class config
{
    public dictionary<string, string> configdata;
    string fullfilename;
    public config(string _filename)
    {
        configdata = new dictionary<string,string>();
        fullfilename = application.startuppath + @"\" + _filename;

        bool hascfgfile =file.exists(application.startuppath + @"\" + _filename);
        if (hascfgfile == false)
        {
            streamwriter writer = new streamwriter(file.create(application.startuppath + @"\" + _filename), encoding.default);
            writer.close();
        }
        streamreader reader = new streamreader(application.startuppath + @"\" + _filename, encoding.default);
        string line;

        int indx = 0;
        while ((line = reader.readline()) != null)
        {
            if (line.startswith(";") || string.isnullorempty(line))
                configdata.add(";" + indx++, line);
            else
            {
                string[] key_value = line.split('=');
                if (key_value.length >= 2)
                    configdata.add(key_value[0], key_value[1]);
                else
                    configdata.add(";" + indx++, line);
            }
        }
        reader.close();
    }

    public string get(string key)
    {
        if (configdata.count <= 0)
            return null;
        else if(configdata.containskey(key))
            return configdata[key].tostring();
        else
            return null;
    }

    public void set(string key, string value)
    {
        if (configdata.containskey(key))
            configdata[key] = value;
        else
            configdata.add(key, value);
    }

    public void save()
    {
        streamwriter writer = new streamwriter(fullfilename,false,encoding.default);
        idictionaryenumerator enu = configdata.getenumerator();
        while (enu.movenext())
        {
            if (enu.key.tostring().startswith(";"))
                writer.writeline(enu.value);
            else
                writer.writeline(enu.key + "=" + enu.value);
        }
        writer.close();
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网