SkylineSoft

莽莽苍节兮 群山巍峨 日月光照兮 纷纭错落 丝竹共振兮 执节者歌 行云流水兮 用心无多 求大道以弹兵兮凌万物而超脱 觅知音因难得兮唯天地与作合
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#类似java属性文件读取器

Posted on 2011-07-11 15:54  Jiangwzh  阅读(696)  评论(0)    收藏  举报
/************************************
版权所有:SkylineSoft版权所有(C)
创建日期:2011-03-31
作  者:天涯居士
电子邮件:Jiangwzh@163.com

系统名称:SkylineSoft.PropertiesReader
模块名称:通用属性配置文件读取
内容摘要:通用属性配置文件读取
**********************************
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace SkylineSoft
{
public class PropertiesReader
{
private Dictionary<string, string> properties = null;

public static PropertiesReader Open(string filePath)
{
return new PropertiesReader(filePath);
}

public PropertiesReader(string filePath)
{
properties
= new Dictionary<string, string>();
Load(filePath);
}

public void Load(string filePath)
{
properties.Clear();

StreamReader reader
= null;
try
{
reader
= new StreamReader(filePath);
string lineContent=reader.ReadLine();
while (lineContent!=null)
{
lineContent
= lineContent.Trim();
if (!string.IsNullOrEmpty(lineContent) && !lineContent.StartsWith("#"))
{
int index = lineContent.IndexOf('=');
if (index > 0)
{
string propName = lineContent.Substring(0,index);

string propValue = string.Empty;
if(index + 1<lineContent.Length)
propValue
= lineContent.Substring(index + 1);

properties.Add(propName,propValue);
}
}
lineContent
=reader.ReadLine();
}
}
finally
{
if (reader != null)
reader.Close();
}
}

public T Get<T>(string propName)
{
if (properties.ContainsKey(propName))
{
string value = properties[propName];
if (!string.IsNullOrEmpty(value))
return (T)Convert.ChangeType(value, typeof(T));
}
return ReflectionUtil.GetTypeDefaultValue<T>();
}

public string GetString(string propName)
{
return Get<string>(propName);
}

public int GetInt(string propName)
{
return Get<int>(propName);
}

public long GetLong(string propName)
{
return Get<long>(propName);
}

public bool GetBoolean(string propName)
{
if (properties.ContainsKey(propName))
{
string value = properties[propName];
return BooleanUtil.ConvertFrom(value);
}
return false;
}

public bool IsExist(string propName)
{
return properties.ContainsKey(propName);
}
}
}