【筆記】C#讀取屬性檔案的類

來源:互聯網
上載者:User
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

測試結果為

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.