这是我的查询代码:
public String getDriveID()
{
String wow = @"win32_logicaldisk.deviceid=\" + @driveID;
ManagementObject disk = new ManagementObject(wow);
disk.Get();
Console.WriteLine(disk["Name"]);
return disk["Name"].ToString();
}
这就是创建方法使用的driveID
字符串的原因:
DriveInfo dInfo = therehasgottobeanotherway[driveList.SelectedIndex];
if (dInfo.IsReady) {
diskWMI dwmi = new diskWMI(dInfo.Name);
}
如果您不熟悉DriveInfo
类,则Name
属性会返回驱动器的名称,例如c:\
我在网上发现这个代码与我正在尝试的完全一样,但是当我尝试使用它时总是会出错:
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
Console.WriteLine(disk["VolumeName"]);
Console.ReadLine();
我打赌发生了格式化错误,但我无法弄清楚要改变什么。
我正在尝试传递驱动器名称,其中包含deviceid=
答案 0 :(得分:1)
public string GetHDDSerialNumber(string drive)
{
//check to see if the user provided a drive letter
//if not default it to "C"
if (drive == "" || drive == null)
{
drive = "C";
}
//create our ManagementObject, passing it the drive letter to the
//DevideID using WQL
ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
//bind our management object
disk.Get();
//return the serial number
return disk["VolumeSerialNumber"].ToString();
}
或您现有的示例,这将适合您
String drive = "c";
ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
disk.Get();
Console.WriteLine(disk["VolumeName"]);
Console.ReadLine();
答案 1 :(得分:0)
不是一个真正的答案,但我可以确认我接受了你的代码并运行了以下内容,对我来说很好:
namespace ConsoleApplication1
{
using System;
using System.Management;
class Program
{
static void Main(string[] args)
{
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
Console.WriteLine(disk["VolumeName"]);
Console.ReadLine();
}
}
}
它在控制台窗口中显示失败的名称。
答案 2 :(得分:0)
从deviceId中删除反斜杠,它应该可以工作。你提到的链接有一个反斜杠:String drive = @“C:\”; => String drive = @“C:”;