我试图获取硬盘的名称或字母,但仍然感到困惑,因为这里有几个功能可以使用。
下面三个代码之间的区别是什么?哪个更好用?
Directory.GetLogicalDrives()
Environment.GetLogicalDrives()
DriveInfo.GetDrives()
结果:
最佳答案
他们都调用这段代码,这只是win32 api的一个包装器GetLogicalDrives function
new EnvironmentPermission(PermissionState.Unrestricted).Demand();
int drives = Win32Native.GetLogicalDrives();
if (drives == 0)
__Error.WinIOError();
uint d = (uint)drives;
int count = 0;
while (d != 0)
{
if (((int)d & 1) != 0) count++;
d >>= 1;
}
String[] result = new String[count];
char[] root = new char[] { 'A', ':', '\\' };
d = (uint)drives;
count = 0;
while (d != 0)
{
if (((int)d & 1) != 0)
{
result[count++] = new String(root);
}
d >>= 1;
root[0]++;
}
return result;
除非
GetDrives
将结果传递给DriveInfo
类// Directory.GetLogicalDrives demands unmanaged code permission
String[] drives = Directory.GetLogicalDrives();
DriveInfo[] di = new DriveInfo[drives.Length];
for(int i=0; i<drives.Length; i++)
di[i] = new DriveInfo(drives[i]);
return di;
所以答案是,没有明显的差别
工具书类
Reference source Directory.GetLogicalDrives()
Reference source Environment.GetLogicalDrives()
Reference source DriveInfo.GetDrives()