【笔记】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

测试结果为



posted @   lazycoding  阅读(663)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示