在转换为 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))
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/