using ControlzEx.Standard; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using TeamAAS_VP.Models; using TeamAAS_VP; using static Org.BouncyCastle.Math.EC.ECCurve; namespace TeamAAS_VP.Core { public static class FileHelper { /// /// 写入Json文件 /// /// 对象 /// 文件路径 public static void WriteJsonFile(object obj, string path) { if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } using (StreamWriter sw = new StreamWriter(path)) { string json = JsonConvert.SerializeObject(obj, Formatting.Indented); sw.Write(JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented)); } } /// /// 读取Json文件 /// /// 对象 /// 文件路径 /// /// public static T ReadJsonFile(string path) { if (File.Exists(path)) { string buffer; using (StreamReader sr = new StreamReader(path)) { buffer = sr.ReadToEnd(); } return JsonConvert.DeserializeObject(buffer); } else { throw new Exception($"文件不存在:[{path}]"); } } /// /// 写入文件 /// /// 对象 /// 文件路径 public static void WriteFile(string content, string path) { if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } using (StreamWriter sw = new StreamWriter(path)) { sw.Write(content); } } /// /// 读取文件 /// /// /// /// public static string ReadFile(string path) { if (File.Exists(path)) { string buffer; using (StreamReader sr = new StreamReader(path)) { buffer = sr.ReadToEnd(); } return buffer; } else { throw new Exception($"文件不存在:[{path}]"); } } /// /// 读取软件设置参数 /// /// public static CurentApplicationSettings ReadApplicationConfiguration() { try { if (File.Exists(FilePath.ApplicationConfigurationPath)) { var config = FileHelper.ReadJsonFile(FilePath.ApplicationConfigurationPath); return config; } else { var config= new CurentApplicationSettings(); FileHelper.WriteJsonFile(config, FilePath.ApplicationConfigurationPath); return config; } } catch (Exception) { return new CurentApplicationSettings(); } } /// /// 保存软件设置参数 /// /// public static void SaveApplicationConfiguration(CurentApplicationSettings config) { try { config.DT=DateTime.Now; FileHelper.WriteJsonFile(config, FilePath.ApplicationConfigurationPath); } catch (Exception) { } } /// /// 检测文件名是否合规 /// /// /// public static bool CheckFileName(string filename) { // // 定义文件名合法性的正则表达式 string pattern = @"^[^-\\/:*?""<>|\x00-\x1F]*$"; // 匹配不包含非法字符的文件名 // 使用正则表达式进行匹配 if (Regex.IsMatch(filename, pattern)) { //Console.WriteLine("输入的名称符合文件名命名规则,并且不包含非法字符。"); return true; } else { //Console.WriteLine("输入的名称不符合文件名命名规则,或者包含非法字符。"); return false; } } } }