1 ///2 /// 内存 3 /// 4 public class VAV_MDDFM_MEM 5 { 6 //定义内存的信息结构 7 [StructLayout(LayoutKind.Sequential)] 8 public struct MEMORY_INFO 9 { 10 public uint dwLength; 11 public uint dwMemoryLoad; 12 public uint dwTotalPhys; 13 public uint dwAvailPhys; 14 public uint dwTotalPageFile; 15 public uint dwAvailPageFile; 16 public uint dwTotalVirtual; 17 public uint dwAvailVirtual; 18 } 19 [DllImport("kernel32")] 20 private static extern void GetWindowsDirectory(StringBuilder WinDir, int count); 21 [DllImport("kernel32")] 22 private static extern void GetSystemDirectory(StringBuilder SysDir, int count); 23 [DllImport("kernel32")] 24 private static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo); 25 26 ///27 /// 打印内存信息 28 /// 29 public static void PrintMemInfo() 30 { 31 Console.WriteLine(GetMemInfo()); 32 } 33 34 ///35 /// 获取内存信息 36 /// 37 ///38 public static string GetMemInfo() 39 { 40 //调用GlobalMemoryStatus函数获取内存的相关信息 41 MEMORY_INFO MemInfo = new MEMORY_INFO(); 42 GlobalMemoryStatus(ref MemInfo); 43 44 StringBuilder sb = new StringBuilder(); 45 46 //*%的内存正在使用 47 sb.Append(MemInfo.dwMemoryLoad.ToString() + "% of the memory is being used " + "\r\n"); 48 //总共的物理内存 49 sb.Append("Physical memory total :" + Utility.ConvertBytes(MemInfo.dwTotalPhys.ToString(), 3) + "GB" + "\r\n"); 50 //可使用的物理内存 51 sb.Append("Use of physical memory :" + Utility.ConvertBytes(MemInfo.dwAvailPhys.ToString(), 3) + "GB" + "\r\n"); 52 //交换文件总大小 53 sb.Append("Total size of the swap file" + Utility.ConvertBytes(MemInfo.dwTotalPageFile.ToString(), 3) + "GB" + "\r\n"); 54 //尚可交换文件大小为 55 sb.Append(" Can still swap file size :" + Utility.ConvertBytes(MemInfo.dwAvailPageFile.ToString(), 3) + "GB" + "\r\n"); 56 //总虚拟内存 57 sb.Append("The Total virtual memory :" + Utility.ConvertBytes(MemInfo.dwTotalVirtual.ToString(), 3) + "GB" + "\r\n"); 58 //未用虚拟内存有 59 sb.Append("Unused virtual memory :" + Utility.ConvertBytes(MemInfo.dwAvailVirtual.ToString(), 3) + "GB" + "\r\n"); 60 // ConvertBytes(totMem, 3) + " GB" 61 return sb.ToString(); 62 } 63 }
1 public class Utility 2 { 3 public static decimal ConvertBytes(string b, int iteration) 4 { 5 long iter = 1; 6 for (int i = 0; i < iteration; i++) 7 iter *= 1024; 8 return Math.Round((Convert.ToDecimal(b)) / Convert.ToDecimal(iter), 2, MidpointRounding.AwayFromZero); 9 } 10 }