93 lines
3.1 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
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 就跳出
}
}
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 等
}
}