using IRaCIS.Core.Domain.Share; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration.Json; using IRaCIS.Core.Infrastructure.Extention; using SharpCompress.Common; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Encodings.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace IRaCIS.Core.Application.Service.Common { [ApiExplorerSettings(GroupName = "Common")] public class SystemMonitor : BaseService { public void GetDiskInfo() { // Get all drives var drives = DriveInfo.GetDrives(); // Loop through each drive and get info foreach (var drive in drives) { if (drive.IsReady && drive.DriveType == DriveType.Fixed) { long totalSize = drive.TotalSize; long availableSpace = drive.AvailableFreeSpace; long usedSpace = totalSize - availableSpace; double usedSpacePercent = (double)usedSpace / totalSize * 100; Console.WriteLine($"Drive {drive.Name}: Total size = {totalSize / (1024 * 1024)} MB, Available space = {availableSpace / (1024 * 1024)} MB, Used space = {usedSpace / (1024 * 1024)} MB ({usedSpacePercent:F2}%)"); } } } public string GetBestStoreDisk() { //默认存储的路径 var defaultStoreRootFolder = Path.Combine((Directory.GetParent(_hostEnvironment.ContentRootPath.TrimEnd('\\'))).IfNullThrowException().FullName, StaticData.Folder.IRaCISDataFolder); var drives = DriveInfo.GetDrives().Where(t => !t.Name.Contains("C") && !t.Name.Contains("c")) .Where(d => d.DriveType == DriveType.Fixed && d.IsReady) .OrderByDescending(d => d.AvailableFreeSpace) .ThenByDescending(d => d.TotalSize - d.TotalFreeSpace); var bestDrive = drives.FirstOrDefault(); var bestStoreRootFolder = string.Empty; //仅仅只有C 盘 if (bestDrive == null) { bestStoreRootFolder = defaultStoreRootFolder; } else { bestStoreRootFolder = drives.FirstOrDefault()?.Name + _hostEnvironment.EnvironmentName; } DriveInfo drive = new DriveInfo(Path.GetPathRoot(defaultStoreRootFolder)); //最优盘符使用率超过百分之80 if (((double)(drive.TotalSize - drive.TotalFreeSpace) / drive.TotalSize) * 100 > 80) { } return bestStoreRootFolder; } public void UpdateAppSettings(string key, string newValue) { #region NewtonSoftJson //// 读取 JSON 文件 //string jsonFilePath = "appsettings.json"; //string jsonString = File.ReadAllText(jsonFilePath); //// 解析 JSON 文件 //var jObject = JsonConvert.DeserializeObject(jsonString); //// 更新或添加配置项 //jObject[key] = newValue; //// 将更新后的 JSON 字符串写入文件 //using var streamWriter = new StreamWriter(jsonFilePath); //using var jsonTextWriter = new JsonTextWriter(streamWriter); //jsonTextWriter.Formatting = Formatting.Indented; //jObject.WriteTo(jsonTextWriter); #endregion // Read JSON file into a JObject //var json = File.ReadAllText("appsettings.json"); //var jObject = JObject.Parse(json); //// Update or add the property //jObject[key] = newValue; //// Get the property to update //var property = jObject.Property(key); //// Get the comment before the property //var comment = property.Previous?.Type == JTokenType.Comment ? property.Previous : null; //// Write the updated JSON back to the file, preserving the comments //using (var reader = new JsonTextReader(new StringReader(json))) //using (var writer = new JsonTextWriter(new StreamWriter("appsettings.json"))) //{ // writer.Formatting = Formatting.Indented; // while (reader.Read()) // { // if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == newValue) // { // // Write the updated property value // writer.WritePropertyName(key); // writer.WriteValue(newValue); // // Write the comment after the property // if (property.Next?.Type == JTokenType.Comment) // { // writer.WriteComment(property.Next.ToString()); // } // continue; // } // // Write all other tokens // writer.WriteToken(reader.TokenType, reader.Value); // } //} //var json = File.ReadAllText("appsettings.json"); //var jObject = JObject.Parse(json, new JsonLoadSettings { CommentHandling = CommentHandling.Load }); //// Update or add the property //jObject[key] = newValue; //// Preserve comments //var settings = new JsonSerializerSettings //{ // PreserveReferencesHandling = PreserveReferencesHandling.Objects, // Formatting = Formatting.Indented, // StringEscapeHandling = StringEscapeHandling.Default //}; //var updatedJson = JsonConvert.SerializeObject(jObject, settings); //File.WriteAllText("appsettings.json", updatedJson); //var json = File.ReadAllText("appsettings.json"); //var jToken = JToken.Parse(json); //// Update or add the property //jToken[key] = newValue; //// Preserve comments //var settings = new JsonSerializerSettings //{ // TypeNameHandling = TypeNameHandling.All, // PreserveReferencesHandling = PreserveReferencesHandling.Objects, // Formatting = Formatting.Indented, // StringEscapeHandling = StringEscapeHandling.Default //}; //var updatedJson = JsonConvert.SerializeObject(jToken, settings); //File.WriteAllText("appsettings.json", updatedJson); // string json = @"{ // // This is a comment // ""Name"": ""John Smith"", // ""Age"": 30, // ""Address"": { // // This is another comment // ""Street"": ""123 Main St"", // ""City"": ""Anytown"", // ""State"": ""CA"", // ""Zip"": ""12345"" // } //}"; // // 使用 Json.NET 库解析 JSON 字符串 // JObject jObject = JObject.Parse(json,new JsonLoadSettings() { CommentHandling=CommentHandling.Load}); // // 修改属性 // jObject["Name"] = "Jane Smith"; // // 将修改后的 JObject 对象序列化为 JSON 字符串并保留注释 // string newJson = jObject.ToString(Formatting.Indented); // // 打印修改后的 JSON 字符串 // Console.WriteLine(newJson); //var json = File.ReadAllText("appsettings.json"); //var jObject = JObject.Parse(json); //var property = jObject.Property(key); //// 如果属性不存在,则添加属性 //if (property == null) //{ // jObject.Add(new JProperty(key, newValue)); //} //// 否则,修改属性 //else //{ // property.Value = newValue; //} //using (var reader = new JsonTextReader(new StringReader(json))) //using (var writer = new JsonTextWriter(new StreamWriter("appsettings.json"))) //{ // writer.Formatting = Formatting.Indented; // while (reader.Read()) // { // if (reader.TokenType == JsonToken.Comment) // { // writer.WriteComment((string)reader.Value); // } // else // { // // 将更改后的JSON写回文件中 // writer.WriteToken(reader.TokenType, jObject); // break; // } // } //} // 读取 JSON 文件,并保留注释 string json = File.ReadAllText("appsettings.json"); JsonSerializerSettings settings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All, Formatting = Formatting.Indented, }; dynamic data = JsonConvert.DeserializeObject(json, settings); // 修改 JSON 对象 data.foo = "bar"; // 将修改后的对象序列化为字符串,并写回原始 JSON 文件 string output = JsonConvert.SerializeObject(data, settings); File.WriteAllText("appsettings.json", output); } } }