ComputerHelp.cs 8.34 KB
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;

namespace Hh.Mes.Common
{
    public class ComputerHelp
    {
        /// <summary>
        /// 端口是否被占用
        /// </summary>
        public static bool PortInUse(int port)
        {
            bool inUse = false;
            var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            var ipEndPoints = ipProperties.GetActiveTcpListeners();
            foreach (IPEndPoint endPoint in ipEndPoints)
            {
                if (endPoint.Port == port)
                {
                    inUse = true;
                    break;
                }
            }
            return inUse;
        }


        /// <summary>
        /// 获取本地IP地址信息
        /// </summary>
        public static string GetAddressIP()
        {
            //获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily==AddressFamily.InterNetwork|| _IPAddress.AddressFamily== AddressFamily.InterNetworkV6)
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }

        /// <summary>
        /// 获取CPU信息
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> GetCPUInfo()
        {
            var result = new Dictionary<string, string>();
            //var mc = new ManagementClass("win32_processor");//创建ManagementClass对象
            //var moc = mc.GetInstances();//获取CPU信息
            //foreach (var mo in moc.Cast<ManagementObject>())
            //{
            //     mo["processorid"].ToString();//获取CUP编号
            //}
            var driveID = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");//查询CPU信息
            int index = 1;
            foreach (var MyXianKa in driveID.Get().Cast<ManagementObject>())
            {
                foreach (var item in MyXianKa.Properties)
                {
                    if (!result.ContainsKey(item.Name))
                    {
                        result.Add(item.Name, item.Value?.ToString());
                    }
                    else
                    {
                        result.Add(item.Name + index, item.Value?.ToString());
                    }
                }
                index++;
                //MyXianKa.["Manufacturer"].ToString();//获取CUP制造商名称
                //MyXianKa["Version"].ToString();//获取CPU版本号
                //MyXianKa["Name"].ToString();//获取CUP产品名称
            }
            return result;
        }

        /// <summary>
        /// 获取CPU占用百分比
        /// </summary>
        /// <returns></returns>
        public static string GetCpuUsage()
        {
            //var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            //return cpuCounter.NextValue();
            var result = string.Empty;
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");
            var cpuItem = searcher.Get().Cast<ManagementObject>().Select(item => new { PercentProcessorTime = item["PercentProcessorTime"] }).FirstOrDefault();
            if (cpuItem != null && cpuItem.PercentProcessorTime != null)
            {
                result = cpuItem.PercentProcessorTime.ToString() + "%";
            }
            else
            {
                result = "获取失败";
            }
            return result;
        }

        /// <summary>
        /// 获取系统内存使用情况
        /// </summary>
        /// <remarks>需要添加 System.Management 的引用</remarks>
        /// <returns>item1=总内存,item2=可使用,item3=已使用,item4=占用百分比</returns>
        public static ValueTuple<string, string, string, string> GetMemery()
        {
            //获取总物理内存大小
            var cimobject1 = new ManagementClass("Win32_PhysicalMemory");
            var moc1 = cimobject1.GetInstances();
            double available = 0, capacity = 0;
            foreach (var mo1 in moc1.Cast<ManagementObject>())
            {
                capacity += Math.Round(long.Parse(mo1.Properties["Capacity"].Value.ToString()) / 1024 / 1024 / 1024.0, 1);
            }
            moc1.Dispose();
            cimobject1.Dispose();


            //获取内存可用大小
            var cimobject2 = new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory");
            var moc2 = cimobject2.GetInstances();
            foreach (var mo2 in moc2.Cast<ManagementObject>())
            {
                available += Math.Round(long.Parse(mo2.Properties["AvailableMBytes"].Value.ToString()) / 1024.0, 1);

            }
            moc2.Dispose();
            cimobject2.Dispose();
            //总内存
            var Total = capacity.ToString() + "G";
            //可使用
            var Sys = available.ToString() + "G";
            //已使用
            string Used = (capacity - available).ToString() + "G";
            //占用百分比
            var Usage = Math.Round((capacity - available) * 100 / capacity, 0).ToString() + "%";
            return (Total, Sys, Used, Usage);
        }

        /// <summary>
        /// 获取磁盘信息
        /// </summary>
        /// <returns></returns>
        public static List<DriveInfo> GetDriveInfos()
        {
            var allDirves = DriveInfo.GetDrives();
            return allDirves.Where(x => x.IsReady).ToList();
        }

        /// <summary>
        /// 获取电脑名称
        /// </summary>
        /// <returns></returns>
        public static string GetComputerName()
        {
            return Environment.MachineName;
        }

        /// <summary>
        /// 获取操作系统信息
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> GetOSInfo()
        {
            var result = new Dictionary<string, string>();
            var mc = new ManagementClass("Win32_OperatingSystem");
            var moc = mc.GetInstances();
            foreach (var mo in moc.Cast<ManagementObject>())
            {
                foreach (var item in mo.Properties)
                {
                    result.Add(item.Name, item.Value?.ToString());
                }
            }
            return result;
        }

        /// <summary>
        /// 执行cmd命令 https://www.cnblogs.com/njl041x/p/3881550.html
        /// 多命令请使用批处理命令连接符:
        /// <![CDATA[
        /// &:同时执行两个命令
        /// |:将上一个命令的输出,作为下一个命令的输入
        /// &&:当&&前的命令成功时,才执行&&后的命令
        /// ||:当||前的命令失败时,才执行||后的命令]]>
        /// 其他请百度
        /// </summary>
        public static void RunCmd(string cmd, string cmdPath, out string output)
        {
            cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
            using (var p = new Process())
            {
                p.StartInfo.FileName = cmdPath;
                p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;          //不显示程序窗口
                p.Start();//启动程序

                //向cmd窗口写入命令
                p.StandardInput.WriteLine(cmd);
                p.StandardInput.AutoFlush = true;
                //获取cmd窗口的输出信息
                output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();//等待程序执行完退出进程
                p.Close();
            }
        }
    }
}