using System; using System.IO; using System.Text; namespace FirewallWindowsServer.Methods { public static class Command { public static void PrintLog(Exception ex) { try { Tool.PrintLog(ex.Message, ex.StackTrace, Path.Combine(AppContext.BaseDirectory, "log\\" + DateTime.Now.ToString("yyyyMMdd") + ".log")); } catch { } } public static void PrintLog(string msg) { try { Tool.PrintLog("", msg, Path.Combine(AppContext.BaseDirectory, "log\\" + DateTime.Now.ToString("yyyyMMdd") + "_info.log")); } catch { } } } public static class Tool { /// /// 打印日志 /// /// public static bool PrintLog(string title, string content, string path) { try { CreateLogDirectory(Path.GetDirectoryName(path)); //往指定文件中追加日志 StreamWriter sw = new StreamWriter(path, true, Encoding.UTF8); sw.WriteLine("产生时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); sw.WriteLine("\t" + title); sw.WriteLine(content); sw.WriteLine(); sw.WriteLine(); sw.Close(); sw.Dispose(); return true; } catch { return false; } } /// /// 创建全路径目录 /// /// public static void CreateLogDirectory(string path) { if (string.IsNullOrEmpty(path)) { return; } string[] paths = path.Split('\\'); string tempPath = ""; foreach (var a in paths) { tempPath += a + "\\"; CreateDirectory(tempPath, ""); //目录不存在的话创建目录 } } /// /// 创建文件夹 /// /// 路径 /// 文件夹名 /// public static string CreateDirectory(string filePath, string folderName = "") { if (string.IsNullOrEmpty(filePath)) { if (string.IsNullOrEmpty(folderName)) { return ""; } } else { if (filePath.Substring(filePath.Length - 1) == @"\") { filePath = filePath.Substring(0, filePath.Length - 1); } } string path = filePath + @"\" + folderName; try { if (!System.IO.Directory.Exists(path)) { Directory.CreateDirectory(path); } } catch (Exception ex) { return null; } return path; } /// /// 获取json配置文件内容 /// /// 配置类实体 /// 要获取的配置文件名(相对当前根目录,appsettings.json) /// 配置类实体 public static T GetSystemConfig(string ConfigFileName = "appsettings.json") { string value = string.Empty; string Root = AppContext.BaseDirectory; string json = GetTxt(Root + "\\" + ConfigFileName); PrintLog("",json, Path.Combine(AppContext.BaseDirectory, "log\\" + DateTime.Now.ToString("yyyyMMdd") + "_info.log")); T config = json.ToModel(); return config; } /// /// 读取指定的文件(UTF-8) /// /// 文件路径 /// public static string GetTxt(string path) { StreamReader sr = new StreamReader(path, Encoding.UTF8); string str = sr.ReadToEnd(); sr.Close(); sr.Dispose(); return str; } } }