日期:2014-05-18  浏览次数:21141 次

C#获得系统内存及开机时间的问题
网上找的获得内存的代码:
--------------------------
private   static   string   GetPhisicalMemory()
{
ManagementObjectSearcher   searcher   =   new   ManagementObjectSearcher();   //用于查询一些如系统信息的管理对象
searcher.Query   =   new   SelectQuery( "Win32_PhysicalMemory ",   " ",   new   string[]   {   "Capacity "   });//设置查询条件
ManagementObjectCollection   collection   =   searcher.Get();   //获取内存容量
ManagementObjectCollection.ManagementObjectEnumerator   em   =   collection.GetEnumerator();

int   capacity   =   0;
while   (em.MoveNext())
{
ManagementBaseObject   baseObj   =   em.Current;
if   (baseObj.Properties[ "Capacity "].Value   !=   null)
{
try
{
capacity   +=   int.Parse(baseObj.Properties[ "Capacity "].Value.ToString());
}
catch
{
return   " ";
}
}
}
return   (capacity/1024/1024).ToString();
}
--------------------------
获得系统启动时间:
--------------------------
TimeSpan   m_WorkTimeTemp   =   new   TimeSpan(Convert.ToInt64(Environment.TickCount)   *   10000);
string   m_WorkTime   =   m_WorkTimeTemp.Days   +   "天 "   +   m_WorkTimeTemp.Hours   +   "小时 "   +   m_WorkTimeTemp.Minutes   +   "分钟 "   +   m_WorkTimeTemp.Seconds   +   "秒 ";
--------------------------
问题:
--------------------------
我在我的机器上(vista   iis7)上面显示的为:
#   内存:1024   MB  
#   开机时间:0天20小时34分钟55秒  
正常

但是在服务器上(win2003   iis6,内存2G)显示为:
#   内存:-2048   MB  
#   开机时间:-6天-9小时-32分钟-25秒  
内存显示为负数,开机时间为43天多,错误如上。。

请问这是为啥?

------解决方案--------------------
关于开机时间
看MSDN
// Sample for the Environment.TickCount property.

// TickCount cycles between Int32.MinValue, which is a negative
// number, and Int32.MaxValue once every 49.8 days. This sample
// removes the sign bit to yield a nonnegative number that cycles
// between zero and Int32.MaxValue once every 24.9 days.

using System;

class Sample
{
public static void Main()
{
int result = Environment.TickCount & Int32.MaxValue;
Console.WriteLine( "TickCount: {0} ", result);
}
}
/*
This example produces the following results:

TickCount: 101931139
*/

你开机时间是不是太长了~~~
------解决方案--------------------
int 类型的范围最大是 2G-1, 2G 内存已经超过范围,所以显示为-2048一点不奇怪

------解决方案--------------------
那些抢分的都归隐了~~~~
呵呵

计算这些东西最好不要使用int
------解决方案--------------------
这是微软的帮助:TickCount最高只能获取到 49.8 天
备注
该属性的值从系统计时器派生,并以 32 位有符号整数的形式存储。因此,如果系统连续运行,TickCount 将在约 24.9 天内从零递增至 Int32.MaxValue,然后跳至 Int32.MinValue(这是一个负数),再在接下来的 24.9 天内递增至零。

TickCount 属性的分辨率不能小于 500 毫秒。

TickCount 不同于 Ticks 属性,后者是自 1/1/0001 中午 12:00 以后经过的 100 毫微秒间隔数。

使用 DateTime.Now 属性可获取此计算机上的当前本地日期和时间。