我正在尝试创建一个可以保存USB设备信息的软件,例如:名称,总空间,可用空间,格式类型等。我使用过DriveInfo []但是我无法工作如何分别为不同的USB设备保存每个INDIVIDUAL片段,因此我知道哪个USB设备适用于哪些信息。我正在尝试将每个USB设备和它的信息保存到文本文件中。这就是我所拥有的:
DriveInfo[] loadedDrives = DriveInfo.GetDrives();
foreach (DriveInfo ld in loadedDrives)
{
if (ld.DriveType == DriveType.Removable)
{
if (ld.IsReady == true)
{
deviceInfo.Add(ld.VolumeLabel + ": , " + ld.TotalSize + ": , " + ld.AvailableFreeSpace + ": , " + ld.DriveFormat);
}
}
}
foreach (String st in deviceInfo)
{
string[] deviceSel;
// DriveInfo dInfo;
deviceSel = st.Split(splitChar);
if (itemSelected.Contains(deviceSel[0]))
{
//Check That USB drive is the one thats selected
MessageBox.Show(deviceSel[0]);
break;
}
}
有没有比我做的更简单的方法?因为我进一步尝试解决问题,代码越复杂。干杯
答案 0 :(得分:0)
好的,你不需要输入一个字符串数组,将它们保存为DriveInfo
:
DriveInfo[] loadedDrives = DriveInfo.GetDrives();
List<DriveInfo> deviceInfo = new List<DriveInfo>();
foreach (DriveInfo ld in loadedDrives)
{
if (ld.DriveType == DriveType.Removable)
{
if (ld.IsReady == true)
{
deviceInfo.Add(ld);
}
}
}
foreach (DriveInfo st in deviceInfo)
{
//can write whatever you want now
}
但是使用linq可以更轻松地完成第一个循环:
DriveInfo[] loadedDrives = DriveInfo.GetDrives();
var deviceInfo = DriveInfo.GetDrives()
.Where(d=>d.DriveType == DriveType.Removable && d.IsReady);