How to get the list of removable disk in c#?

孤街浪徒 提交于 2019-11-30 01:22:07

问题


I want to get the list of removable disk in c#. I want to skip the local drives. Because i want the user to save the file only in removable disk.


回答1:


You will need to reference System.IO for this method.

var driveList = DriveInfo.GetDrives();

foreach (DriveInfo drive in driveList)
{
    if (drive .DriveType == DriveType.Removable)
    {
    //Add to RemovableDrive list or whatever activity you want
    }    
}

Or for the LINQ fans:

var driveList = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Removable);



Added
As for the Saving part, as far as I know I don't think you can restrict where the user is allowed to save to using a SaveFileDialog, but you could complete a check after you have shown the SaveFileDialog.

if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
  if (CheckFilePathIsOfRemovableDisk(saveFileDialog.FileName) == true)
  {
  //carry on with save
  }
  else
  {
  MessageBox.Show("Must save to Removable Disk, location was not valid");
  }
}

OR

The best option would be to create your own Save Dialog, which contains a tree view, only showing the removable drives and their contents for the user to save to! I would recommend this option.

Hope this helps




回答2:


How about:

var removableDrives = from d in System.IO.DriveInfo.GetDrives()
                      where d.DriveType == DriveType.Removable;



回答3:


You can also use WMI to get the list of removable drives.

ManagementObjectCollection drives = new ManagementObjectSearcher (
     "SELECT Caption, DeviceID FROM Win32_DiskDrive WHERE InterfaceType='USB'"
).Get();

Edited based on comment:

After you get the list of drives get there GUID's and add them to SaveFileDialogInstance.CustomPlaces collection.

The code below need some tweaking...

System.Windows.Forms.SaveFileDialog dls = new System.Windows.Forms.SaveFileDialog();
dls.CustomPlaces.Clear();
dls.CustomPlaces.Add(AddGuidOfTheExternalDriveOneByOne);
....
....
dls.ShowDialog();



回答4:


This article looks to do the trick:

http://zayko.net/post/How-to-get-list-of-removable-drives-installed-on-a-computer-(C).aspx



来源:https://stackoverflow.com/questions/1124463/how-to-get-the-list-of-removable-disk-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!