superstar_v2/Env.cs

93 lines
3.1 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
namespace Utils
{
public static class Env
{
private static string KtvPath = "";
private static readonly List<string> KtvPaths = new()
{
@"\\sshost\KTVSuperstar",
@"\\pc101\KTVSuperstar"
};
private static readonly Dictionary<string, string> _values = new(StringComparer.OrdinalIgnoreCase);
static Env()
{
foreach (var path in KtvPaths)
{
var configPath = Path.Combine(path, "config.ini");
if (File.Exists(configPath))
{
KtvPath = path;
2025-07-08 13:37:12 +08:00
Console.WriteLine("找到設定檔:" + configPath);
foreach (var line in File.ReadAllLines(configPath))
{
var trimmed = line.Trim();
if (string.IsNullOrWhiteSpace(trimmed) || trimmed.StartsWith("#")) continue;
var index = trimmed.IndexOf('=');
if (index < 0) continue;
var key = trimmed[..index].Trim();
var value = trimmed[(index + 1)..].Trim();
if (value.StartsWith("\"") && value.EndsWith("\""))
value = value[1..^1];
_values[key] = value;
}
return; // 找到一份 config 就跳出
}
}
2025-07-08 13:37:12 +08:00
Console.WriteLine("所有指定目錄都找不到 config.ini");
}
public static string Get(string key, string fallback = "") =>
_values.TryGetValue(key, out var value) ? value : fallback;
public static bool GetBool(string key, bool fallback = false) =>
_values.TryGetValue(key, out var value) && bool.TryParse(value, out var result)
? result : fallback;
public static int GetInt(string key, int fallback = 0) =>
_values.TryGetValue(key, out var value) && int.TryParse(value, out var result)
? result : fallback;
public static string GetPath(string key, string fallback = "")
{
if (string.IsNullOrWhiteSpace(KtvPath))
{
Console.WriteLine("⚠️ KtvPath 尚未設定,將使用 fallback。");
return fallback;
}
var path = Path.Combine(KtvPath, key);
if (Directory.Exists(path))
{
return path;
}
else
{
Console.WriteLine($"⚠️ 找不到目錄:{path},使用 fallback{fallback}");
return fallback;
}
}
public static string GetDBConnection()
{
return $"Server={Get("DBServer", "localhost")};Port={Get("DBPort", "3306")};Database={Get("Database", "test")};User={Get("DBUser", "root")};Password={Get("DBPassword", "")};";
}
// 如需支援更多型別可自行擴充GetFloat, GetDouble, GetDateTime 等
}
}