0

我正在尝试创建一个可以保存 USB 设备信息的软件,例如:名称、总空间、可用空间、格式类型等。我使用过 DriveInfo[],但我不知道如何分别为不同的 USB 设备保存每个单独的片段,这样我就知道哪个 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;
                }

            }

有没有比我做的更简单的方法?因为我越是尝试解决问题,代码就越复杂。干杯

4

1 回答 1

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);
于 2013-10-20T10:03:58.997 回答