C# 读取文件中的配置信息

文章目录

      • 定义
      • 使用
        • 文件格式
        • 代码

C#读取文件并处理;C# 读取文件中的配置信息。
在有的程序中,需要从本地文件中读取配置信息,以进行初始化。

定义

定义一个静态函数来获取文件信息。StreamReader 类。

/// 
/// 读取参数文件
/// 
/// 文件的路径
/// 字典格式的参数列表
public static Dss GetParams(string fPath)
{
    if (File.Exists(fPath))                         // 检验路径是否存在
    {
        Dss d = new Dss();                          // 待使用数据
        using (StreamReader sr = new StreamReader("Config.txt")) // 创建StreamReader对象读取文件
        {
            string row = null;                          // 按行读
            while (!((row = sr.ReadLine()) is null))    // 只要还有数据,就一直读
            {
                if (row.StartsWith("//")) continue;     // 注释部分                   
                row = row.Trim(new char[] { '\r', '\n', ',', ' ' });    // 删除头尾无关数据
                row = row.Replace(" ", "");                             // 删除空格字符
                //将字符串str以空格为分隔符分为几部分,分别装到字符串数组segs中
                string[] segs = row.Split('=');
                // 下面检验是否为无效数据(key-value可能为空)
                if (segs.Length < 2 || string.IsNullOrEmpty(segs[0]) || string.IsNullOrEmpty(segs[1])) continue;
                d[segs[0]] = segs[1];                   // 添加进字典
            }
            return d;
        }
    }
    return null;
}

使用

文件格式

本程序操作的文件格式如下:

参数为: key=value
注释以//打头。
按行划分

C# 读取文件中的配置信息_第1张图片
代码
public static void Main()
{
    // 打开文件,文件位置为项目的bin/debug目录下。
    Dss prms = GetParams("Config.txt");
	
    if (prms != null)
    {
        foreach (var item in prms)		// 打印参数列表
        {
            Console.WriteLine($"{item.Key}={item.Value}");
        }
    }
    Console.ReadLine();
}

输出:

ServerName=Wlb
DataBaseName=Test

你可能感兴趣的:(C#项目,笔记,c#,开发语言)