code-layout/GeneratorCode/Configure/NConfig.cs

122 lines
3.5 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Timers;
using IniParser;
using IniParser.Model;
using JetBrains.Annotations;
namespace GeneratorCode.Configure
{
public static class NConfig
{
private static string _cfgFileName = @".\config.ini";
private static IniData _cfgData = null;
public delegate void ConfigChangedHandle();
public static event ConfigChangedHandle OnConfigChanged;
private static void ConfigChanged()
{
OnConfigChanged?.Invoke();
}
private static void LoadCfgFromFile()
{
try
{
if (!File.Exists(_cfgFileName))
{
var fs = new FileStream(_cfgFileName, FileMode.Create, FileAccess.Write);
var ws = new StreamWriter(fs);
ws.WriteLine("; 应用程序配置文件\n");
}
FileIniDataParser iniPraser = new FileIniDataParser();
iniPraser.Parser.Configuration.CommentString = ";";
_cfgData = iniPraser.ReadFile(_cfgFileName);
//Trace.WriteLine(_cfgData);
}
catch (Exception e)
{
Trace.WriteLine(e.Message);
}
}
public static void InitConfigure()
{
var cfgTask = new List<string>();
var appPath = Process.GetCurrentProcess().MainModule.FileName;
Trace.WriteLine("Application: " + appPath);
Trace.WriteLine("Directory: " + Path.GetDirectoryName(appPath));
Trace.WriteLine("File: " + Path.GetFileName(appPath));
var fw = new FileSystemWatcher(@"E:\", @"my.cfg")
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
//Filter = _cfgFileName,
//Path = Path.GetDirectoryName(appPath),
IncludeSubdirectories = false,
};
fw.Changed += (sender, e) =>
{
//if (Path.GetFileName(appPath) != _cfgFileName) return;
lock (cfgTask)
{
if (cfgTask.Contains(e.FullPath)) return;
cfgTask.Add(e.FullPath);
}
var tm = new Timer(1000) { AutoReset = false };
tm.Elapsed += (obj, args) =>
{
lock (cfgTask)
{
cfgTask.Remove(e.FullPath);
LoadCfgFromFile();
ConfigChanged();
// LogOut("File: " + e.FullPath + " ==> " + e.ChangeType.ToString() + "\n");
}
};
tm.Start();
};
fw.EnableRaisingEvents = true;
LoadCfgFromFile();
}
public static T GetCfgValue<T>([NotNull] string secName, [NotNull] string keyName, T defValue = default(T))
{
var ret = defValue;
if (_cfgData.Equals(null))
{
return ret;
}
try
{
ret = (T) Convert.ChangeType(_cfgData[secName][keyName], typeof(T));
}
catch(Exception e)
{
Trace.WriteLine("[" + _cfgData[secName][keyName] + "] :" + e.Message);
ret = defValue;
throw(e);
}
return ret;
}
}
}