【笔记】C#读取属性文件的类
View Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.IO;
6
7 namespace CTest
8 {
9 class PropertyFileOperator
10 {
11 private StreamReader sr = null;
12 /// <summary>
13 /// 构造函数
14 /// </summary>
15 /// <param name="strFilePath">文件路径</param>
16 public PropertyFileOperator(string strFilePath)
17 {
18 sr = new StreamReader(strFilePath);
19 }
20 /// <summary>
21 /// 关闭文件流
22 /// </summary>
23 public void Close()
24 {
25 sr.Close();
26 sr = null;
27 }
28 /// <summary>
29 /// 根据键获得值字符串
30 /// </summary>
31 /// <param name="strKey">键</param>
32 /// <returns>值</returns>
33 public string GetPropertiesText(string strKey)
34 {
35 string strResult = string.Empty;
36 string str = string.Empty;
37 sr.BaseStream.Seek(0, SeekOrigin.Begin);
38 while ((str = sr.ReadLine()) != null)
39 {
40 if (str.Substring(0, str.IndexOf('=')).Equals(strKey))
41 {
42 strResult = str.Substring(str.IndexOf('=') + 1);
43 break;
44 }
45 }
46 return strResult;
47 }
48 /// <summary>
49 /// 根据键获得值数组
50 /// </summary>
51 /// <param name="strKey">键</param>
52 /// <returns>值数组</returns>
53 public string[] GetPropertiesArray(string strKey)
54 {
55 string strResult = string.Empty;
56 string str = string.Empty;
57 sr.BaseStream.Seek(0, SeekOrigin.Begin);
58 while ((str = sr.ReadLine()) != null)
59 {
60 if (str.Substring(0, str.IndexOf('=')).Equals(strKey))
61 {
62 strResult = str.Substring(str.IndexOf('=') + 1);
63 break;
64 }
65 }
66 return strResult.Split(',');
67 }
68 }
69 }
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
测试结果为