c# - 从 Collection 元素到 Int64 的转换错误。指定的转换无效

标签 c# .net type-conversion

在转换为 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();  
} 

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

最佳答案

它是 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.

附言:

1) 实际上,如果您确实需要 Int64,您可以执行以下转换:

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

2) 你可以阅读 this article by Eric Lippert , 阐明相关异常的本质。

关于c# - 从 Collection 元素到 Int64 的转换错误。指定的转换无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12632744/

相关文章:

c# - 从 Unity 中的另一个脚本调用 IEnumerator 方法并获取其返回值

C# 区域设置混淆

c# - 安全 Windows 模拟?

swift - 数据类型转换问题

c# - TypeConverter 无法从某些基本类型转换为相同的基本类型

Python 3 - 通过类型转换读取csv文件

c# - 创建用于 Entity Framework 6 的表达式

.net - 如何在 Maxscript 中使用点网字符串.Split

java - Java 的动态代理的.Net 等价物是什么?

c# - 从 Microsoft lifecams 拍照