.Net实践:C#如何读取、写入INI配置文件

来源:http://www.97world.com/archives/2872

 

最近接触到INI配置文件的读写,虽然很久以前微软就推荐使用注册表来代替INI配置文件,现在在Visual Studio上也有专门的.Net配置文件格式,但是看来看去还是INI配置文件顺眼。事实上.Net的XML格式配置文件在功能上更加强大,我也更推荐 大家使用这种类型的配置文件来进行.Net软件的开发,我之所以使用INI配置文件,无非是想尝一下鲜和个人习惯而已。

    C#本身没有提供访问INI配置文件的方法,但是我们可以使用WinAPI提供的方法来处理INI文件的读写,代码很简单!网上有大量现成的代码,这里只是作为记录和整理,方便日后使用。

INI配置文件的组成?

    INI文件是文本文件,由若干节(section)组成,在每个带中括号的节名称下,是若干个关键词(key)及其对应的值(Value),这些关键词(key)属于位于关键词(key)上的节(section)。
[Section]
Key1=Value1
Key2=Value2

核心代码

    这里为了使用方便,我们将读写INI配置文件的关键代码封装在一个类中,网上的其他相关代码也是这样做的。

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
 
namespace ToolsLibrary
{
    public class IniFile
    {
        public string path;             //INI文件名 
         
        //声明写INI文件的API函数
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
         
        //声明读INI文件的API函数
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
 
        //类的构造函数,传递INI文件的路径和文件名
        public IniFile(string INIPath) 
        { 
            path = INIPath; 
        } 
 
        //写INI文件
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, path);
        }
 
        //读取INI文件
        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, path);
            return temp.ToString();
        }
      
    } 
}

在以后使用的时候,我们只要实例化一个IniFile对象,即可通过这个对象中的方法读写INI配置文件。

例如读取INI配置文件中的值

IniFile ini = new IniFile("C://config.ini"); 
BucketName = ini.IniReadValue("operatorinformation","bucket");
OperatorName = ini.IniReadValue("operatorinformation", "operatorname");
OperatorPwd = ini.IniReadValue("operatorinformation", "operatorpwd");

将值写入INI配置文件中

IniFile ini = new IniFile("C://config.ini"); 
ini.IniWriteValue("operatorinformation", "bucket", BucketName);
ini.IniWriteValue("operatorinformation", "operatorname", OperatorName);
ini.IniWriteValue("operatorinformation", "operatorpwd", OperatorPwd);

 

 

 

 

posted @ 2014-03-01 17:42  s7ven  阅读(1775)  评论(0编辑  收藏  举报