INI文件读取帮助

项目中时常会用到不少的外部配置参数,又或者对一些CODE预先定义.使用INI文件来存储不失为一个好办法

 

 
  
public class INIHelper
{

/// <summary>
/// 读取INI文件专用类
/// </summary>
private bool succeeded = false ;
private Hashtable cfgParam = new Hashtable();

public bool Succeeded { get { return succeeded; } }
public string this [ string ParamName]
{
get
{
if (cfgParam.ContainsKey(ParamName))
return cfgParam[ParamName].ToString();
else
return "" ;
}
}

public int Length
{
get { return cfgParam.Count; }
}
/// <summary>
/// 读取指定INI文件中的配置信息
/// </summary>
/// <param name="file"> 配置文件的完整路径名 </param>
/// <param name="section"> 配置文件中的节名 </param>
public DbConfig( string file, string section)
{
string Section = " [ " + section + " ] " ;
string fileName = file.Substring(file.LastIndexOf( ' \\ ' ) + 1 );

GetInitializeConfig(file, Section);

// 如果MainSysinfoPath不为空,则从MainSysinfoPath指定的文件中读取配置信息
if ( this .succeeded && cfgParam.Contains( " MainSysinfoPath " ))
{
string path = this [ " MainSysinfoPath " ].TrimEnd( ' \\ ' ); // 允许路径尾部带反斜杆“\”或不带反斜杆“\”
if (path != "" ) GetInitializeConfig(path + @" \ " + fileName, Section);
}
}

private void GetInitializeConfig( string filePath, string Section)
{
try
{
StreamReader sr
= new StreamReader(filePath, System.Text.Encoding.Default);
string readLine = null ;
bool readEnd = false ;
string [] keyWord;

while ((readLine = sr.ReadLine()) != null )
{
if (readLine == Section) // 是指定的节,则开始读取配置信息
{
while ((readLine = sr.ReadLine()) != null )
{
if (readLine != "" ) // 跳过空行
{
if (readLine.Substring( 0 , 1 ) == " [ " ) // 是另一新节,则结束本次的读取
{
readEnd
= true ;
break ;
}

keyWord
= readLine.Split( ' = ' );
cfgParam[keyWord[
0 ].Trim()] = keyWord[ 1 ].Trim();
}
}
}

if (readEnd == true ) break ;
}
sr.Close();
succeeded
= true ;
}
catch
{
succeeded
= false ;
}
}
}

 

读取速度不错....当然别弄个几百M的配置文件哦....

转载于:https://www.cnblogs.com/loverjohni/archive/2010/05/14/1735795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值