using System; using System.IO; using System.Xml.Serialization; namespace KevServer { public class WebConfig { /// /// 图件路径 /// public string MapDirectory { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Maps"); /// /// 底图路径 /// public string BaseMapDirectory { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BaseMaps"); /// /// 监听地址 /// public string ListenUrl { get; set; } public static string ConfigFile { get; set; } public static string StartupPath { get; set; } private static WebConfig instance = null; private WebConfig() { var path = StartupPath; if (string.IsNullOrEmpty(path)) { path = System.AppDomain.CurrentDomain.BaseDirectory; } ConfigFile = Path.Combine(path, "KevWebConfig.xml"); } public static WebConfig Instance { get { if (instance == null) { instance = new WebConfig(); if (instance.Open() == false) { DirectoryInfo di = new DirectoryInfo(StartupPath); string strServerPath = di.Parent.FullName; instance.MapDirectory = Path.Combine(strServerPath, "Maps"); instance.BaseMapDirectory = Path.Combine(strServerPath, "BaseMaps"); instance.Save(); } } return instance; } set { instance = value; } } /// /// 打开配置文件. /// /// 是否成功 public bool Open() { string strFile = ConfigFile; if (string.IsNullOrEmpty(strFile) || !File.Exists(strFile)) { return false; } try { using (StreamReader reader = new StreamReader(strFile)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(WebConfig)); instance = xmlSerializer.Deserialize(reader) as WebConfig; } } catch (Exception ex) { Console.WriteLine($"加载 WebConfig 配置文件失败: ${ex.Message}"); return false; } return true; } public void Save() { string strFile = ConfigFile; if (!File.Exists(strFile)) { File.Create(strFile).Close(); } using (StreamWriter writer = new StreamWriter(strFile)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(WebConfig)); XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces(); nameSpace.Add(string.Empty, string.Empty); xmlSerializer.Serialize(writer, instance, nameSpace); } } } }