瀏覽代碼

硬件信息支持获取硬件序列号
树形实体增加获取根节点和支持单个实体平铺开
增加decimal的一些扩展方法

懒得勤快 4 年之前
父節點
當前提交
cfadb69102

+ 6 - 4
Masuit.Tools.Abstractions/Extensions/BaseType/ValueTypeConvertExtensions.cs

@@ -49,13 +49,15 @@ namespace Masuit.Tools
         }
         }
 
 
         /// <summary>
         /// <summary>
-        /// 转decimal
+        /// 字符串转decimal
         /// </summary>
         /// </summary>
-        /// <param name="s"></param>
+        /// <param name="s">源字符串</param>
+        /// <param name="round">小数位数</param>
+        /// <param name="defaultValue">转换失败的默认值</param>
         /// <returns>int类型的数字</returns>
         /// <returns>int类型的数字</returns>
-        public static decimal ToDecimal(this double s)
+        public static decimal ToDecimal(this string s, int round, decimal defaultValue = 0)
         {
         {
-            return new decimal(s);
+            return Math.Round(s.TryConvertTo(defaultValue), round);
         }
         }
 
 
         /// <summary>
         /// <summary>

+ 5 - 0
Masuit.Tools.Abstractions/Hardware/CpuInfo.cs

@@ -54,6 +54,11 @@
         /// 核心温度
         /// 核心温度
         /// </summary>
         /// </summary>
         public double Temperature { get; set; }
         public double Temperature { get; set; }
+
+        /// <summary>
+        /// 序列号
+        /// </summary>
+        public string SerialNumber { get; set; }
     }
     }
 #pragma warning restore 1591
 #pragma warning restore 1591
 }
 }

+ 9 - 0
Masuit.Tools.Abstractions/Hardware/DiskInfo.cs

@@ -0,0 +1,9 @@
+namespace Masuit.Tools.Hardware
+{
+    public class DiskInfo
+    {
+        public string SerialNumber { get; set; }
+        public string Model { get; set; }
+        public float Total { get; set; }
+    }
+}

+ 16 - 119
Masuit.Tools.Abstractions/Hardware/SystemInfo.cs

@@ -230,6 +230,7 @@ namespace Masuit.Tools.Hardware
                     MaxClockSpeed = mo.Properties["MaxClockSpeed"].Value.ToString(),
                     MaxClockSpeed = mo.Properties["MaxClockSpeed"].Value.ToString(),
                     Type = mo.Properties["Name"].Value.ToString(),
                     Type = mo.Properties["Name"].Value.ToString(),
                     DataWidth = mo.Properties["DataWidth"].Value.ToString(),
                     DataWidth = mo.Properties["DataWidth"].Value.ToString(),
+                    SerialNumber = mo.Properties["ProcessorId"].Value.ToString(),
                     DeviceID = mo.Properties["DeviceID"].Value.ToString(),
                     DeviceID = mo.Properties["DeviceID"].Value.ToString(),
                     NumberOfCores = Convert.ToInt32(mo.Properties["NumberOfCores"].Value),
                     NumberOfCores = Convert.ToInt32(mo.Properties["NumberOfCores"].Value),
                     Temperature = GetCPUTemperature()
                     Temperature = GetCPUTemperature()
@@ -579,124 +580,38 @@ namespace Masuit.Tools.Hardware
 
 
         #region 获取磁盘空间
         #region 获取磁盘空间
 
 
-        /// <summary>
-        /// 获取磁盘可用空间
-        /// </summary>
-        /// <returns></returns>
-        public static Dictionary<string, string> DiskFree()
-        {
-            try
-            {
-                var dic = new Dictionary<string, string>();
-                var mos = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
-                foreach (var mo in mos.Get())
-                {
-                    if (null != mo["DeviceID"] && null != mo["FreeSpace"])
-                    {
-                        dic.Add(mo["DeviceID"].ToString(), FormatBytes(float.Parse(mo["FreeSpace"].ToString())));
-                    }
-                }
-
-                return dic;
-            }
-            catch (Exception)
-            {
-                return new Dictionary<string, string>()
-                {
-                    { "null", "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
-                };
-            }
-        }
-
-        /// <summary>
-        /// 获取磁盘总空间
-        /// </summary>
-        /// <returns></returns>
-        public static Dictionary<string, string> DiskTotalSpace()
-        {
-            try
-            {
-                var dic = new Dictionary<string, string>();
-                using var mos = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
-                foreach (var mo in mos.Get())
-                {
-                    if (null != mo["DeviceID"] && null != mo["Size"])
-                    {
-                        dic.Add(mo["DeviceID"].ToString(), FormatBytes(float.Parse(mo["Size"].ToString())));
-                    }
-                }
-
-                return dic;
-            }
-            catch (Exception)
-            {
-                return new Dictionary<string, string>();
-            }
-        }
-
+        private static readonly List<DiskInfo> DiskInfos = new();
 
 
         /// <summary>
         /// <summary>
-        /// 获取磁盘用空间
+        /// 获取磁盘可用空间
         /// </summary>
         /// </summary>
         /// <returns></returns>
         /// <returns></returns>
-        public static Dictionary<string, string> DiskUsedSpace()
+        private static List<DiskInfo> GetDiskInfo()
         {
         {
             try
             try
             {
             {
-                var dic = new Dictionary<string, string>();
-                using var mos = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
-                foreach (var mo in mos.Get())
+                if (DiskInfos.Count > 0)
                 {
                 {
-                    if (null != mo["DeviceID"] && null != mo["Size"])
-                    {
-                        var free = mo["FreeSpace"];
-                        dic.Add(mo["DeviceID"].ToString(), FormatBytes(float.Parse(mo["Size"].ToString()) - free.ToString().ToDouble()));
-                    }
+                    return DiskInfos;
                 }
                 }
 
 
-                return dic;
-            }
-            catch (Exception)
-            {
-                return new Dictionary<string, string>()
-                {
-                    { "null", "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。" }
-                };
-            }
-        }
-
-        /// <summary>
-        /// 获取磁盘使用率
-        /// </summary>
-        /// <returns></returns>
-        public static Dictionary<string, float> DiskUsage()
-        {
-            try
-            {
-                var dic = new Dictionary<string, float>();
-                using var mos = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
-                foreach (var mo in mos.Get())
+                using var mc = new ManagementClass("Win32_DiskDrive");
+                using var moc = mc.GetInstances();
+                foreach (var mo in moc)
                 {
                 {
-                    var device = mo["DeviceID"];
-                    if (null != device)
+                    DiskInfos.Add(new DiskInfo()
                     {
                     {
-                        var free = mo["FreeSpace"];
-                        var total = mo["Size"];
-                        if (null != total && total.ToString().TryConvertTo<float>() > 0)
-                        {
-                            dic.Add(device.ToString(), 1 - free.ToString().TryConvertTo<float>() / total.ToString().TryConvertTo<float>());
-                        }
-                    }
+                        Total = float.Parse(mo["Size"].ToString()),
+                        Model = mo["Model"].ToString(),
+                        SerialNumber = mo["SerialNumber"].ToString(),
+                    });
                 }
                 }
 
 
-                return dic;
+                return DiskInfos;
             }
             }
             catch (Exception)
             catch (Exception)
             {
             {
-                return new Dictionary<string, float>()
-                {
-                    { "未能获取到当前计算机的磁盘信息,可能是当前程序无管理员权限,如果是web应用程序,请将应用程序池的高级设置中的进程模型下的标识设置为:LocalSystem;如果是普通桌面应用程序,请提升管理员权限后再操作。", 0 }
-                };
+                return new List<DiskInfo>();
             }
             }
         }
         }
 
 
@@ -713,24 +628,6 @@ namespace Masuit.Tools.Hardware
         #region Win32API声明 
         #region Win32API声明 
 
 
 #pragma warning disable 1591
 #pragma warning disable 1591
-        [DllImport("kernel32")]
-        public static extern void GetWindowsDirectory(StringBuilder winDir, int count);
-
-        [DllImport("kernel32")]
-        public static extern void GetSystemDirectory(StringBuilder sysDir, int count);
-
-        [DllImport("kernel32")]
-        public static extern void GetSystemInfo(ref CPU_INFO cpuinfo);
-
-        [DllImport("kernel32")]
-        public static extern void GlobalMemoryStatus(ref MemoryInfo meminfo);
-
-        [DllImport("kernel32")]
-        public static extern void GetSystemTime(ref SystemtimeInfo stinfo);
-
-        [DllImport("IpHlpApi.dll")]
-        public static extern uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);
-
         [DllImport("User32")]
         [DllImport("User32")]
         public static extern int GetWindow(int hWnd, int wCmd);
         public static extern int GetWindow(int hWnd, int wCmd);
 
 

+ 3 - 3
Masuit.Tools.Abstractions/Masuit.Tools.Abstractions.csproj

@@ -7,7 +7,7 @@
     <LangVersion>9.0</LangVersion>
     <LangVersion>9.0</LangVersion>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <CodeAnalysisRuleSet />
     <CodeAnalysisRuleSet />
-    <Version>2.4.2.9</Version>
+    <Version>2.4.2.10</Version>
     <Authors>懒得勤快</Authors>
     <Authors>懒得勤快</Authors>
     <Description>Masuit.Tools基础公共库</Description>
     <Description>Masuit.Tools基础公共库</Description>
     <Copyright>懒得勤快,长空X</Copyright>
     <Copyright>懒得勤快,长空X</Copyright>
@@ -20,9 +20,9 @@
     <RepositoryType>Github</RepositoryType>
     <RepositoryType>Github</RepositoryType>
     <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
     <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
     <PackageRequireLicenseAcceptance>False</PackageRequireLicenseAcceptance>
     <PackageRequireLicenseAcceptance>False</PackageRequireLicenseAcceptance>
-    <FileVersion>2.4.2.9</FileVersion>
+    <FileVersion>2.4.2.10</FileVersion>
     <Company>ldqk.org</Company>
     <Company>ldqk.org</Company>
-    <AssemblyVersion>2.4.2.9</AssemblyVersion>
+    <AssemblyVersion>2.4.2.10</AssemblyVersion>
     <PackageLicenseUrl>https://github.com/ldqk/Masuit.Tools/blob/master/LICENSE</PackageLicenseUrl>
     <PackageLicenseUrl>https://github.com/ldqk/Masuit.Tools/blob/master/LICENSE</PackageLicenseUrl>
     <EmbedUntrackedSources>true</EmbedUntrackedSources>
     <EmbedUntrackedSources>true</EmbedUntrackedSources>
     <IncludeSymbols>true</IncludeSymbols>
     <IncludeSymbols>true</IncludeSymbols>

+ 36 - 3
Masuit.Tools.Abstractions/Models/TreeExtensions.cs

@@ -16,11 +16,12 @@ namespace Masuit.Tools.Models
         /// <param name="items"></param>
         /// <param name="items"></param>
         /// <param name="func"></param>
         /// <param name="func"></param>
         /// <returns></returns>
         /// <returns></returns>
-        public static IEnumerable<T> Filter<T>(this IEnumerable<T> items, Func<T, bool> func) where T : ITreeChildren<T>
+        public static IEnumerable<T> Filter<T>(this IEnumerable<T> items, Func<T, bool> func) where T : class, ITreeChildren<T>
         {
         {
             var results = new List<T>();
             var results = new List<T>();
             foreach (var item in items.Where(i => i != null))
             foreach (var item in items.Where(i => i != null))
             {
             {
+                item.Children ??= new List<T>();
                 item.Children = item.Children.Filter(func).ToList();
                 item.Children = item.Children.Filter(func).ToList();
                 if (item.Children.Any() || func(item))
                 if (item.Children.Any() || func(item))
                 {
                 {
@@ -37,7 +38,7 @@ namespace Masuit.Tools.Models
         /// <param name="item"></param>
         /// <param name="item"></param>
         /// <param name="func"></param>
         /// <param name="func"></param>
         /// <returns></returns>
         /// <returns></returns>
-        public static IEnumerable<T> Filter<T>(this T item, Func<T, bool> func) where T : ITreeChildren<T>
+        public static IEnumerable<T> Filter<T>(this T item, Func<T, bool> func) where T : class, ITreeChildren<T>
         {
         {
             return new[] { item }.Filter(func);
             return new[] { item }.Filter(func);
         }
         }
@@ -48,12 +49,34 @@ namespace Masuit.Tools.Models
         /// <typeparam name="T"></typeparam>
         /// <typeparam name="T"></typeparam>
         /// <param name="items"></param>
         /// <param name="items"></param>
         /// <returns></returns>
         /// <returns></returns>
-        public static IEnumerable<T> Flatten<T>(this IEnumerable<T> items) where T : ITreeChildren<T>
+        public static IEnumerable<T> Flatten<T>(this IEnumerable<T> items) where T : class, ITreeChildren<T>
         {
         {
             var result = new List<T>();
             var result = new List<T>();
             foreach (var item in items)
             foreach (var item in items)
             {
             {
                 result.Add(item);
                 result.Add(item);
+                item.Children ??= new List<T>();
+                result.AddRange(item.Children.Flatten());
+            }
+
+            return result;
+        }
+
+        /// <summary>
+        /// 平铺开
+        /// </summary>
+        /// <typeparam name="T"></typeparam>
+        /// <returns></returns>
+        public static IEnumerable<T> Flatten<T>(this T p) where T : class, ITreeChildren<T>
+        {
+            var result = new List<T>()
+            {
+                p
+            };
+            foreach (var item in p.Children)
+            {
+                result.Add(item);
+                item.Children ??= new List<T>();
                 result.AddRange(item.Children.Flatten());
                 result.AddRange(item.Children.Flatten());
             }
             }
 
 
@@ -124,8 +147,18 @@ namespace Masuit.Tools.Models
         /// </summary>
         /// </summary>
         public static string Path<T>(this T tree, Func<T, string> selector) where T : ITreeParent<T> => GetFullPath(tree, selector);
         public static string Path<T>(this T tree, Func<T, string> selector) where T : ITreeParent<T> => GetFullPath(tree, selector);
 
 
+        /// <summary>
+        /// 根节点
+        /// </summary>
+        public static T Root<T>(this T tree) where T : ITreeParent<T> => GetRoot(tree, t => t.Parent);
+
         private static string GetFullPath<T>(T c, Func<T, string> selector) where T : ITreeParent<T> => c.Parent != null ? GetFullPath(c.Parent, selector) + "/" + selector(c) : selector(c);
         private static string GetFullPath<T>(T c, Func<T, string> selector) where T : ITreeParent<T> => c.Parent != null ? GetFullPath(c.Parent, selector) + "/" + selector(c) : selector(c);
 
 
+        /// <summary>
+        /// 根节点
+        /// </summary>
+        public static T GetRoot<T>(T c, Func<T, T> selector) where T : ITreeParent<T> => c.Parent != null ? GetRoot(c.Parent, selector) : c;
+
         /// <summary>
         /// <summary>
         /// 递归取出所有下级
         /// 递归取出所有下级
         /// </summary>
         /// </summary>

+ 6 - 3
Masuit.Tools.Core/Masuit.Tools.Core.csproj

@@ -20,10 +20,10 @@
         <UserSecretsId>830c282f-f7c1-42be-8651-4cd06ac8e73f</UserSecretsId>
         <UserSecretsId>830c282f-f7c1-42be-8651-4cd06ac8e73f</UserSecretsId>
         <RepositoryType>Github</RepositoryType>
         <RepositoryType>Github</RepositoryType>
         <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
         <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
-        <Version>2.4.2.9</Version>
-        <FileVersion>2.4.2.9</FileVersion>
+        <Version>2.4.2.10</Version>
+        <FileVersion>2.4.2.10</FileVersion>
         <Company>ldqk.org</Company>
         <Company>ldqk.org</Company>
-        <AssemblyVersion>2.4.2.9</AssemblyVersion>
+        <AssemblyVersion>2.4.2.10</AssemblyVersion>
         <Authors>懒得勤快X</Authors>
         <Authors>懒得勤快X</Authors>
         <RepositoryUrl>https://github.com/ldqk/Masuit.Tools</RepositoryUrl>
         <RepositoryUrl>https://github.com/ldqk/Masuit.Tools</RepositoryUrl>
         <EmbedUntrackedSources>true</EmbedUntrackedSources>
         <EmbedUntrackedSources>true</EmbedUntrackedSources>
@@ -155,6 +155,9 @@
         <Compile Include="..\Masuit.Tools.Abstractions\Hardware\SystemInfo.cs">
         <Compile Include="..\Masuit.Tools.Abstractions\Hardware\SystemInfo.cs">
             <Link>Hardware\SystemInfo.cs</Link>
             <Link>Hardware\SystemInfo.cs</Link>
         </Compile>
         </Compile>
+        <Compile Include="..\Masuit.Tools.Abstractions\Hardware\DiskInfo.cs">
+            <Link>Hardware\DiskInfo.cs</Link>
+        </Compile>
         <Compile Include="..\Masuit.Tools.Abstractions\Hardware\SystemtimeInfo.cs">
         <Compile Include="..\Masuit.Tools.Abstractions\Hardware\SystemtimeInfo.cs">
             <Link>Hardware\SystemtimeInfo.cs</Link>
             <Link>Hardware\SystemtimeInfo.cs</Link>
         </Compile>
         </Compile>

+ 3 - 0
Masuit.Tools/Masuit.Tools.csproj

@@ -122,6 +122,9 @@
     <Compile Include="..\Masuit.Tools.Abstractions\Hardware\DiskData.cs">
     <Compile Include="..\Masuit.Tools.Abstractions\Hardware\DiskData.cs">
       <Link>Hardware\DiskData.cs</Link>
       <Link>Hardware\DiskData.cs</Link>
     </Compile>
     </Compile>
+    <Compile Include="..\Masuit.Tools.Abstractions\Hardware\DiskInfo.cs">
+      <Link>Hardware\DiskInfo.cs</Link>
+    </Compile>
     <Compile Include="..\Masuit.Tools.Abstractions\Hardware\MemoryInfo.cs">
     <Compile Include="..\Masuit.Tools.Abstractions\Hardware\MemoryInfo.cs">
       <Link>Hardware\MemoryInfo.cs</Link>
       <Link>Hardware\MemoryInfo.cs</Link>
     </Compile>
     </Compile>

二進制
Masuit.Tools/Properties/AssemblyInfo.cs


+ 1 - 1
Masuit.Tools/package.nuspec

@@ -4,7 +4,7 @@
     <!--*-->
     <!--*-->
     <id>Masuit.Tools.Net</id>
     <id>Masuit.Tools.Net</id>
     <!--*-->
     <!--*-->
-    <version>2.4.2.9</version>
+    <version>2.4.2.10</version>
     <title>Masuit.Tools</title>
     <title>Masuit.Tools</title>
     <!--*-->
     <!--*-->
     <authors>masuit.com</authors>
     <authors>masuit.com</authors>