c# .net读取Linux系统基本信息

1、获取系统版本、架构、名称

方式一:从/etc/os-release文件读取系统发行版信息

public class LinuxSystemInfo
{
    // 操作系统名称(如Ubuntu、CentOS)
    public string OsName { get; set; } 
    // 操作系统版本
    public string OsVersion { get; set; }
    // 内核版本
    public string KernelVersion { get; set; }
    
    // 系统架构(如x86_64)
    public string Architecture { get; set; }
    
    // 发行版ID(如ubuntu、centos)
    public string Id { get; set; }
    
    // 版本代号(如focal、bullseye)
    public string VersionCodename { get; set; }
}
 /// <summary>
/// 从/etc/os-release文件读取系统发行版信息
/// </summary>
private static void ReadOsRelease(LinuxSystemInfo info)
{
var osPlatform = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" :
                        RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "Linux" :
                        RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "macOS" : "Unknown";
 if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
 {
     const string filePath = "/etc/os-release";

     if (!System.IO.File.Exists(filePath))
     {
         throw new FileNotFoundException("未找到系统信息文件", filePath);
     }

     var lines = System.IO.File.ReadAllLines(filePath)
         .Where(line => !string.IsNullOrWhiteSpace(line) && line.Contains('='))
         .ToDictionary(
             line => line.Split('=')[0].Trim(),
             line => line.Split('=')[1].Trim().Trim('"')
         );

     // 提取关键信息
     if (lines.TryGetValue("NAME", out string name))
         info.OsName = name;

     if (lines.TryGetValue("VERSION", out string version))
         info.OsVersion = version;

     if (lines.TryGetValue("ID", out string id))
         info.Id = id;

     if (lines.TryGetValue("VERSION_CODENAME", out string codename))
         info.VersionCodename = codename;
 }
}

方式二:.NET版本支持

需要.NET Core 2.0 + 或.NET 5+,这些版本对 Linux 有良好的跨平台支持

RuntimeInformation类在这些版本中可用

//当前操作系统
var osPlatform = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" :
                         RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "Linux" :
                         RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "macOS" : "Unknown";
var se = RuntimeInformation.FrameworkDescription; //.NET框架版本 例如:.NET 8.0.14
var se1 = RuntimeInformation.OSDescription; //内核版本 例如:Ubuntu 22.04.5 LTS
var se2 = RuntimeInformation.OSArchitecture; //架构 例如:X64或X32

2、获取系统运行时间

方法一:c#静态属性

//Environment.TickCount64 是 C# 中 Environment 类的一个静态属性,用于获取当前系统启动后经过的毫秒数,返回值为 long 类型
long milliseconds = Environment.TickCount64;
            TimeSpan uptime = TimeSpan.FromMilliseconds(milliseconds);
            DMP_System_BasicInfo.systemUptime_d = uptime.Days.Ext_IsDBNull();
            DMP_System_BasicInfo.systemUptime_h = uptime.Hours.Ext_IsDBNull();
            DMP_System_BasicInfo.systemUptime_m = uptime.Minutes.Ext_IsDBNull();
            DMP_System_BasicInfo.systemUptime_s = uptime.Seconds.Ext_IsDBNull();

方法二:读取linux系统的文本文件

      // 获取系统运行时间
      if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
      {
          const string uptimeFilePath = "/proc/uptime";

          // 检查文件是否存在
          if (!System.IO.File.Exists(uptimeFilePath))
          {
              log.A("Error:无法找到系统运行时间文件/proc/uptime", LogType.error);
          }

          try
          {
              // 读取文件内容,格式通常为"352297.47 335488.22"
              // 第一个数值是系统运行的总秒数(包含小数)
              string uptimeContent =System.IO.File.ReadAllText(uptimeFilePath).Trim();
              string[] parts = uptimeContent.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

              if (parts.Length >= 1 && double.TryParse(parts[0], out double totalSeconds))
              {
                  var timeinfo= TimeSpan.FromSeconds(totalSeconds);
                  DMP_System_BasicInfo.systemUptime_d = timeinfo.Days.Ext_IsDBNull();
                  DMP_System_BasicInfo.systemUptime_h = timeinfo.Hours.Ext_IsDBNull();
                  DMP_System_BasicInfo.systemUptime_m = timeinfo.Minutes.Ext_IsDBNull();
                  DMP_System_BasicInfo.systemUptime_s = timeinfo.Seconds.Ext_IsDBNull();
              }
          }
          catch (Exception ex)
          {
              log.A("Error:获取系统运行时间失败,"+ex.Message, LogType.error);
          }
      }

3、获取Linux系统CPU使用率

        /// <summary>
        /// cpu使用率
        /// </summary>
        /// <returns></returns>
        public static double GetCpuUsage()
        {
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    var stat1 = System.IO.File.ReadAllLines("/proc/stat");
                    var cpuLine1 = stat1.First(l => l.StartsWith("cpu "));
                    var parts1 = cpuLine1.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    long idle1 = long.Parse(parts1[4]);
                    long total1 = parts1.Skip(1).Select(long.Parse).Sum();

                    // 等待200ms再次采样
                    Thread.Sleep(200);

                    var stat2 = System.IO.File.ReadAllLines("/proc/stat");
                    var cpuLine2 = stat2.First(l => l.StartsWith("cpu "));
                    var parts2 = cpuLine2.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    long idle2 = long.Parse(parts2[4]);
                    long total2 = parts2.Skip(1).Select(long.Parse).Sum();

                    // 计算差值
                    long idleDiff = idle2 - idle1;
                    long totalDiff = total2 - total1;

                    return Math.Round((1.0 - (double)idleDiff / totalDiff) * 100, 1);
                }
                return 0;
            }
            catch { return 0; }
        }

4、获取Linux系统内存使用率

/// <summary>
/// 内存使用率
/// </summary>
/// <returns></returns>
private static double GetMemoryUsage()
{
    try
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            var memInfo = System.IO.File.ReadAllLines("/proc/meminfo");
            var totalMem = ParseMemValue(memInfo.First(l => l.StartsWith("MemTotal:")));
            var availableMem = ParseMemValue(memInfo.First(l => l.StartsWith("MemAvailable:")));

            if (totalMem > 0)
            {
                return Math.Round(((totalMem - availableMem) * 100.0) / totalMem, 1);
            }
        }
    }
    catch { /* 忽略错误 */ }
    return 0;
}

 5、获取系统磁盘内存使用情况

    //磁盘空间对象
    public class DMP_System_SpaceInfo {
        /// <summary>
        /// T::磁盘名::0:0:*:1
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// T::总空间::0:0:*:1
        /// </summary>
        public string totalSizeGB { get; set; }
        /// <summary>
        /// T::可用空间::0:0:*:1
        /// </summary>
        public string availableFreeSpaceGB { get; set; }
        /// <summary>
        /// T::已使用::0:0:*:1
        /// </summary>
        public string usedSpaceGB { get; set; }
        /// <summary>
        /// T::使用率::0:0:*:1
        /// </summary>
        public string usedPercent { get; set; }
    }
      //系统磁盘信息-磁盘使用率
      /*   var info= DriveInfo.GetDrives().Where(d => d.IsReady)
           .ToDictionary(d => d.Name, d => (d.TotalFreeSpace, d.TotalSize));*/
      var DiskInfo = DriveInfo.GetDrives().Where(d => d.IsReady).ToList();
      List<DMP_System_SpaceInfo> DMP_System_SpaceInfos = new List<DMP_System_SpaceInfo>();
      double stotalsize = 0;
      double susedSpace = 0;
      for (int i = 0; i < DiskInfo.Count(); i++)
      {
          DriveInfo driveInfo = (DriveInfo)DiskInfo[i];
          DMP_System_SpaceInfo sinfo = new DMP_System_SpaceInfo();
          sinfo.Name= driveInfo.Name;
          // 字节转换为GB (1 GB = 1024^3 字节 = 1,073,741,824 字节)
          double totalSizeGB = driveInfo.TotalSize / (1024.0 * 1024 * 1024);
          sinfo.totalSizeGB = (totalSizeGB).ToString("F2");
          double availableFreeSpaceGB = driveInfo.AvailableFreeSpace / (1024.0 * 1024 * 1024);
          sinfo.availableFreeSpaceGB = (availableFreeSpaceGB).ToString("F2");
          double usedSpaceGB = totalSizeGB - availableFreeSpaceGB;
          sinfo.usedSpaceGB = (totalSizeGB - availableFreeSpaceGB).ToString("F2");
          sinfo.usedPercent = ((usedSpaceGB / totalSizeGB) * 100).ToString("F2");
          DMP_System_SpaceInfos.Add(sinfo);
          stotalsize = stotalsize + totalSizeGB;
          susedSpace = susedSpace + usedSpaceGB;
      }
      DMP_System_Info.DMP_System_BasicInfo.SpaceInfo_value = (susedSpace*100 / stotalsize).ToString("F0");
      DMP_System_Info.DMP_System_SpaceInfos = DMP_System_SpaceInfos;

 

posted @ 2025-08-18 12:21  じ逐梦  阅读(55)  评论(0)    收藏  举报