另一个代替使用的解决方案ManagementObjectSearcher
是以DiskPart.exe
编程方式使用,但我的代码是一个静态解决方案(使用正则表达式会更好),但可以工作很长时间。
它需要具有更高执行权限的清单文件(添加新元素 > 应用程序清单文件并更改requestedExecutionLevel
为<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
. 以获取更多信息:https ://stackoverflow.com/a/43941461/5830773 )
然后您可以使用以下代码获取驱动器列表DiskPart.exe
:
// execute DiskPart programatically
Process process = new Process();
process.StartInfo.FileName = "diskpart.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.StandardInput.WriteLine("list volume");
process.StandardInput.WriteLine("exit");
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// extract information from output
string table = output.Split(new string[] { "DISKPART>" }, StringSplitOptions.None)[1];
var rows = table.Split(new string[] { "\n" }, StringSplitOptions.None);
for (int i = 3; i < rows.Length; i++)
{
if (rows[i].Contains("Volume"))
{
int index = Int32.Parse(rows[i].Split(new string[] { " " }, StringSplitOptions.None)[3]);
string label = rows[i].Split(new string[] { " " }, StringSplitOptions.None)[8];
Console.WriteLine($@"Volume {index} {label}:\");
}
}
这提供了来自 DiskPart 的以下输出,但您可以根据需要对其进行自定义:
Volume 0 C:\
Volume 1 D:\
Volume 2 F:\
Volume 3 G:\
Volume 4 I:\
Volume 5 H:\
现在按驱动器号搜索很明显:
public int GetIndexOfDrive(string drive)
{
drive = drive.Replace(":", "").Replace(@"\", "");
// execute DiskPart programatically
Process process = new Process();
process.StartInfo.FileName = "diskpart.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.StandardInput.WriteLine("list volume");
process.StandardInput.WriteLine("exit");
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// extract information from output
string table = output.Split(new string[] { "DISKPART>" }, StringSplitOptions.None)[1];
var rows = table.Split(new string[] { "\n" }, StringSplitOptions.None);
for (int i = 3; i < rows.Length; i++)
{
if (rows[i].Contains("Volume"))
{
int index = Int32.Parse(rows[i].Split(new string[] { " " }, StringSplitOptions.None)[3]);
string label = rows[i].Split(new string[] { " " }, StringSplitOptions.None)[8];
if (label.Equals(drive))
{
return index;
}
}
}
return -1;
}
用法:
Console.WriteLine(GetIndexOfDrive(@"D:\")); // returns 1 on my computer