You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OMS.NET/Common/ServerConfig.cs

108 lines
3.6 KiB
C#

using System.Text;
namespace OMS.NET.Common
{
public sealed class ServerConfig
{
private Dictionary<string, string> _config = new();
/// <summary>
/// 连接数据库的连接字符串 default Empty
/// 默认不带数据库名称
/// </summary>
public string ConnectionString => _config.TryGetValue("ConnectionString", out string? value)
? value
: "";
/// <summary>
/// 数据库名称 default map_db
/// </summary>
public string DataBaseName => _config.TryGetValue("DataBaseName", out string? value)
? value
: "map_db";
/// <summary>
/// 监听端口 default 8080
/// </summary>
public string ListenPort => _config.TryGetValue("ListenPort", out string? value)
? value
: "8080";
/// <summary>
/// 是否开启匿名登录 default false
/// </summary>
public string AnonymousLogin => _config.TryGetValue("AnonymousLogin", out string? value)
? value
: "false";
/// <summary>
/// 服务器最大在线人数
/// default 20
/// </summary>
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();
}
}
}