RAMHelper.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Management;
  3. namespace AIDiagnosisDemo.Infrastucture
  4. {
  5. /// <summary>
  6. /// 文件大小单位,包括从B至PB共六个单位。
  7. /// </summary>
  8. public enum FileSizeUnit
  9. {
  10. B,
  11. KB,
  12. MB,
  13. GB,
  14. TB,
  15. PB
  16. }
  17. internal class RAMHelper
  18. {
  19. /// <summary>
  20. /// 获得总共的物理内存的大小,单位 (Byte),如果获取失败,返回 -1.
  21. /// </summary>
  22. /// <returns></returns>
  23. public static long GetTotalPhysicalMemory()
  24. {
  25. long capacity = 0;
  26. try
  27. {
  28. foreach (ManagementObject mo1 in new ManagementClass("Win32_PhysicalMemory").GetInstances())
  29. capacity += long.Parse(mo1.Properties["Capacity"].Value.ToString());
  30. }
  31. catch (Exception ex)
  32. {
  33. capacity = -1;
  34. Console.WriteLine(ex.Message);
  35. }
  36. return capacity;
  37. }
  38. /// <summary>
  39. /// 获得已使用的物理内存的大小,单位 (Byte),如果获取失败,返回 -1.
  40. /// </summary>
  41. /// <returns></returns>
  42. public static long GetAvailablePhysicalMemory()
  43. {
  44. long capacity = 0;
  45. try
  46. {
  47. foreach (ManagementObject mo1 in new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory").GetInstances())
  48. capacity += long.Parse(mo1.Properties["AvailableBytes"].Value.ToString());
  49. }
  50. catch (Exception ex)
  51. {
  52. capacity = -1;
  53. Console.WriteLine(ex.Message);
  54. }
  55. return capacity;
  56. }
  57. /// <summary>
  58. /// 根据指定的文件大小单位,对输入的文件大小(字节表示)进行转换。
  59. /// </summary>
  60. /// <param name="filesize">文件文件大小,单位为字节。</param>
  61. /// <param name="targetUnit">目标单位。</param>
  62. /// <returns></returns>
  63. public static double ToFileFormat(long filesize, FileSizeUnit targetUnit = FileSizeUnit.MB)
  64. {
  65. double size = -1;
  66. switch (targetUnit)
  67. {
  68. case FileSizeUnit.KB: size = filesize / 1024.0; break;
  69. case FileSizeUnit.MB: size = filesize / 1024.0 / 1024; break;
  70. case FileSizeUnit.GB: size = filesize / 1024.0 / 1024 / 1024; break;
  71. case FileSizeUnit.TB: size = filesize / 1024.0 / 1024 / 1024 / 1024; break;
  72. case FileSizeUnit.PB: size = filesize / 1024.0 / 1024 / 1024 / 1024 / 1024; break;
  73. default: size = filesize; break;
  74. }
  75. return size;
  76. }
  77. }
  78. }