/************************************
版权所有: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);
}
}
}