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
測試結果為