您的位置:首页 > 编程语言 > C#

【笔记】C#读取属性文件的类

2012-02-22 21:06 375 查看
View Code

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

namespace CTest
{
class PropertyFileOperator
{
private StreamReader sr = null;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="strFilePath">文件路径</param>
public PropertyFileOperator(string strFilePath)
{
sr = new StreamReader(strFilePath);
}
/// <summary>
/// 关闭文件流
/// </summary>
public void Close()
{
sr.Close();
sr = null;
}
/// <summary>
/// 根据键获得值字符串
/// </summary>
/// <param name="strKey">键</param>
/// <returns>值</returns>
public string GetPropertiesText(string strKey)
{
string strResult = string.Empty;
string str = string.Empty;
sr.BaseStream.Seek(0, SeekOrigin.Begin);
while ((str = sr.ReadLine()) != null)
{
if (str.Substring(0, str.IndexOf('=')).Equals(strKey))
{
strResult = str.Substring(str.IndexOf('=') + 1);
break;
}
}
return strResult;
}
/// <summary>
/// 根据键获得值数组
/// </summary>
/// <param name="strKey">键</param>
/// <returns>值数组</returns>
public string[] GetPropertiesArray(string strKey)
{
string strResult = string.Empty;
string str = string.Empty;
sr.BaseStream.Seek(0, SeekOrigin.Begin);
while ((str = sr.ReadLine()) != null)
{
if (str.Substring(0, str.IndexOf('=')).Equals(strKey))
{
strResult = str.Substring(str.IndexOf('=') + 1);
break;
}
}
return strResult.Split(',');
}
}
}


C#读取属性文件的类。其中,属性文件的形式应该像这样

property=value

这种情况适用于GetPropertiesText

prope=value1,value2...

这种情况适用于GetPropertiesArray

给出一个测试的例子。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace CTest
{
class Program
{
static void Main(string[] args)
{
PropertyFileOperator pro = new PropertyFileOperator("test");
string[] s=pro.GetPropertiesArray("test");
foreach(string s1 in s)
Console.WriteLine(s1);

}

}
}


其中属性文件为test

内容为

test=value1,vaule2,value3

测试结果为

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: