【发布时间】:2016-03-03 03:01:42
【问题描述】:
如何获取 PC 中的所有驱动器。以及每个驱动器的类型和每个驱动器的可用空间
即系统驱动器、CD 驱动器、DVD 驱动器、可移动设备等。
如果系统连接了新驱动器,则可能是笔式驱动器或外置硬盘。
如何在连接时检测到它们?
【问题讨论】:
如何获取 PC 中的所有驱动器。以及每个驱动器的类型和每个驱动器的可用空间
即系统驱动器、CD 驱动器、DVD 驱动器、可移动设备等。
如果系统连接了新驱动器,则可能是笔式驱动器或外置硬盘。
如何在连接时检测到它们?
【问题讨论】:
要获取驱动器列表,您可以使用System.IO.DriveInfo 类:
foreach(var drive in DriveInfo.GetDrives())
{
Console.WriteLine("Drive Type: {0}", drive.DriveType);
Console.WriteLine("Drive Size: {0}", drive.TotalSize);
Console.WriteLine("Drive Free Space: {0}", drive.TotalFreeSpace);
}
很遗憾,这并没有提供监听 USB 密钥插入的方法。您可以查看另一个问题:
【讨论】:
public string getalldrivestotalnfreespace()
{
string s = " Drive Free Space TotalSpace FileSystem %Free Space DriveType\n\r========================================================================================\n\r";
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
double ts = 0;
double fs = 0;
double frprcntg = 0;
long divts = 1024 * 1024 * 1024;
long divfs = 1024 * 1024 * 1024;
string tsunit = "GB";
string fsunit = "GB";
if (drive.IsReady)
{
fs = drive.TotalFreeSpace;
ts = drive.TotalSize;
frprcntg = (fs / ts) * 100;
if (drive.TotalSize < 1024)
{
divts =1; tsunit = "Byte(s)";
}
else if (drive.TotalSize < (1024*1024))
{
divts = 1024; tsunit = "KB";
}
else if (drive.TotalSize < (1024 * 1024*1024))
{
divts = 1024*1024; tsunit = "MB";
}
//----------------------
if (drive.TotalFreeSpace < 1024)
{
divfs = 1; fsunit = "Byte(s)";
}
else if (drive.TotalFreeSpace < (1024 * 1024))
{
divfs = 1024; fsunit = "KB";
}
else if (drive.TotalFreeSpace < (1024 * 1024 * 1024))
{
divfs = 1024 * 1024; fsunit = "MB";
}
s = s +
" " + drive.VolumeLabel.ToString() +
"[" + drive.Name.Substring(0, 2) +
"]\t" + String.Format("{0,10:0.0}", ((fs / divfs)).ToString("N2")) + fsunit +
String.Format("{0,10:0.0}", (ts / divts).ToString("N2")) + tsunit +
"\t" + drive.DriveFormat.ToString() + "\t\t" + frprcntg.ToString("N2") + "%"+
"\t\t" + drive.DriveType.ToString();
s = s + "\n\r";
}
}
return s;
}
输出应如下所示:-
【讨论】:
insert picture 图标。这样它就可以内嵌显示,而不需要点击您的链接。
Environment.GetLogicalDrives();
【讨论】:
您可以很容易地获得驱动器和信息
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
Console.WriteLine(drive.Name);
Console.WriteLine(drive.TotalSize);
}
有一篇关于检测添加/删除驱动器的好文章on CodeProject
【讨论】:
Environment.GetLogicalDrives();
【讨论】:
WMI libraries 可能会有所帮助。还有一篇关于这个的代码项目文章:
【讨论】:
这是您第一个问题的答案。要获取所有逻辑驱动器,您可以尝试以下操作:
string[] drives = Environment.GetLogicalDrives();
【讨论】:
System.IO.DriveInfo 类是开始的地方。 DriveType 属性可以告诉您要查找的内容。
【讨论】:
获取当前连接的所有驱动器:
DriveInfo[] allDrives = DriveInfo.GetDrives();
对于检测,您必须侦听 WMI 事件。看看这个:http://www.techtalkz.com/c-c-sharp/182048-need-detect-insertion-removal-usb-drive.html
【讨论】: