2

转换为 Int64 或任何大数字时,我在以下代码上遇到问题。任何帮助表示赞赏。

public static void GetDiskspace(string MachineName, string DriveLetter) 
{ 
  ConnectionOptions options = new ConnectionOptions(); 
  ManagementScope scope = new ManagementScope("\\\\" + MachineName + "\\root\\cimv2",  
  options); 
  scope.Connect(); 
  SelectQuery query1 = new SelectQuery("Select * from Win32_LogicalDisk"); 

  ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope, query1); 
  ManagementObjectCollection queryCollection1 = searcher1.Get(); 

  foreach (ManagementObject mo in queryCollection1) 
  { 
      // Display Logical Disks information 

      if (mo["Name"].Equals(DriveLetter.ToUpper()+":"))
          if (((Int64)mo["FreeSpace"]) < (1024 * 1024 * 100)) //100GB  <<----HERE IS WHERE I GET THE ERROR
          {
              Console.WriteLine(MachineName + " ALERT. LOW SPACE ON DRIVE " + mo["Name"]);
              Console.WriteLine();
              Console.WriteLine("              Disk Name : {0}", mo["Name"]);
              Console.WriteLine("              Disk Size : {0}", mo["Size"]);
              Console.WriteLine("              FreeSpace : {0}", mo["FreeSpace"]);
              Console.WriteLine("          Disk DeviceID : {0}", mo["DeviceID"]);
              Console.WriteLine("        Disk VolumeName : {0}", mo["VolumeName"]);
              Console.WriteLine("        Disk SystemName : {0}", mo["SystemName"]);
              Console.WriteLine("Disk VolumeSerialNumber : {0}", mo["VolumeSerialNumber"]);
              Console.WriteLine();
          }
  } 
  string line; 
  line = Console.ReadLine();  
} 

编辑:将“大小”更改为“自由空间”。

4

2 回答 2

4

它被ulong装箱了object。所以你只能将它拆箱到ulong(即UInt64)。

 if (((UInt64)mo["Size"]) < (1024 * 1024 * 100))

在此处输入图像描述

看看Win32_LogicalDisk 类

class Win32_LogicalDisk : CIM_LogicalDisk
{
    ...
    uint64   Size;
    ...
};

Win32_LogicalDisk类属性描述的摘录:

尺寸

Data type: uint64 
Access type: Read-only Size of the disk drive.
This property is inherited from CIM_LogicalDisk.

PS:

1)实际上,如果你确实需要Int64,你可以做以下演员:

(Int64)(UInt64)mo["Size"]

2)您可以阅读Eric Lippert 的这篇文章,阐明所讨论异常的本质。

于 2012-09-28T02:25:45.060 回答
2

改为TryParse检查该值是否为有效数字。

long number;
bool result = Int64.TryParse(mo["Size"], out number);
于 2012-09-28T02:25:34.297 回答