获取配置文件内容
之前一直不知道怎么读取配置文件内容的,看了挺多,什么放在appsetting.json这种文件啊,xml啊,等等等等。不仅配置麻烦,还要引入很多dll,我就取个值这么麻烦?
实际上完全可以直接写进文件,文件里每一行key和value用空格隔开。public static class ConfigManager
{
private static readonly Dictionary<string, string> ConfigDictionary = new();
public static void InitConfig(string filePath)
{
try
{
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith("#"))
{
continue;
}
var strArray = line.Split(" ");
if (strArray.Length != 2)
{
continue;
}
ConfigDictionary.TryAdd(strArray[0], strArray[1]);
// Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
public static string GetConfigValue(string key)
{
if (!ConfigDictionary.ContainsKey(key))
{
return "";
}
return ConfigDictionary[key];
}
}
就是这样了。在InitConfig方法里传入文件路径初始化。GetConfigValue取值。