| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 447 人关注过本帖
标题:C#中读写INI配置文件
只看楼主 加入收藏
saiyo55
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2010-8-5
结帖率:0
收藏
 问题点数:0 回复次数:1 
C#中读写INI配置文件
在作应用系统开发时,管理配置是必不可少的。例如数据库服务器的配置、安装和更新配置等等。由于Xml的兴起,现在的配置文件大都是以xml文档来存储。比如Visual 自身的配置文件Mashine.config,的配置文件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
using System.Runtime.InteropServices;

namespace PubOp
{
    public class OperateIniFile
    {
        API函数声明#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

        读Ini文件#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

        写Ini文件#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的值来代替。
 


搜索更多相关主题的帖子: 服务器 数据库 配置文件 moncler creates 
2010-10-26 16:42
zhoufeng1988
Rank: 15Rank: 15Rank: 15Rank: 15Rank: 15
来 自:北京
等 级:贵宾
威 望:27
帖 子:1432
专家分:6329
注 册:2009-5-31
收藏
得分:0 
Well。
2010-10-26 22:41
快速回复:C#中读写INI配置文件
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.026087 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved