using System.Text; namespace OMS.NET.Common { public sealed class ServerConfig { private Dictionary _config = new(); /// /// 连接数据库的连接字符串 default Empty /// 默认不带数据库名称 /// public string ConnectionString => _config.TryGetValue("ConnectionString", out string? value) ? value : ""; /// /// 数据库名称 default map_db /// public string DataBaseName => _config.TryGetValue("DataBaseName", out string? value) ? value : "map_db"; /// /// 监听端口 default 8080 /// public string ListenPort => _config.TryGetValue("ListenPort", out string? value) ? value : "8080"; /// /// 是否开启匿名登录 default false /// public string AnonymousLogin => _config.TryGetValue("AnonymousLogin", out string? value) ? value : "false"; /// /// 服务器最大在线人数 /// default 20 /// public string MaxUser => _config.TryGetValue("ServerConfigMaxUser", out string? value) ? value : "20"; public ServerConfig() { //do nothing,everything default } public ServerConfig(string configPath) { if (!File.Exists(configPath)) { throw new FileNotFoundException("服务器配置文件未找到, path: " + configPath); } foreach (var line in File.ReadLines(configPath)) { // 忽略空行和注释行 var trimmedLine = line.Trim(); if (string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith("#")) { continue; } // 去掉行尾的注释 var commentIndex = trimmedLine.IndexOf('#'); if (commentIndex > -1) { trimmedLine = trimmedLine[..commentIndex].Trim(); } // 查找冒号的位置 var separatorIndex = trimmedLine.IndexOf(':'); if (separatorIndex > -1) { // 获取键和值,并去除冒号前后的空格 var key = trimmedLine[..separatorIndex].Trim(); var value = trimmedLine[(separatorIndex + 1)..].Trim(); // 将键值对添加到字典中 _config[key] = value; } } } public override string ToString() { StringBuilder stringBuilder = new(); foreach (var key in _config.Keys) { stringBuilder.AppendLine($"{key}:{_config[key]}"); } //通过属性访问 // stringBuilder.AppendLine("====加载默认值后的配置项===="); // Type type = this.GetType(); // PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); // foreach (PropertyInfo property in properties) // { // if (property.CanRead && !property.CanWrite) // { // object? value = property.GetValue(this); // stringBuilder.AppendLine($"{property.Name} = {value}"); // } // } return stringBuilder.ToString(); } } }