2012-09-28 66 views
2

當轉換爲Int64或任何大數字時,Im對下列代碼有問題。任何幫助表示讚賞。從Collection元素到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(); 
} 

編輯:更改「大小」爲「FreeSpace」。

+0

'mo [「Size」]。GetType()'? –

+0

價值96782405632 – hagensoft

回答

4

ulong盒裝入object。因此,您只能將其開箱到ulong(即UInt64)。

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

enter image description here

看一看Win32_LogicalDisk class

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)你能讀懂this article by Eric Lippert,澄清有關的異常的本質。

+0

ulong對象謝謝,這工作! – hagensoft

2

使用​​而不是檢查值是否有效數字或不。

long number; 
bool result = Int64.TryParse(mo["Size"], out number); 
相關問題