如何在c#中获取可移动磁盘列表?

我想在c#中获取可移动磁盘列表。 我想跳过本地驱动器。 因为我希望用户只将文件保存在可移动磁盘中。

您需要为此方法引用System.IO

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

或者对于LINQ粉丝:

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

添加
至于Saving部分,据我所知,我不认为你可以限制用户可以使用SaveFileDialog保存的位置,但是你可以在显示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"); } } 

要么

最好的选择是创建自己的保存对话框,其中包含树视图,仅显示可移动驱动器及其内容供用户保存! 我会推荐这个选项。

希望这可以帮助

怎么样:

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

您还可以使用WMI获取可移动驱动器列表。

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

根据评论编辑:

获得驱动器列表后,获取GUID并将它们添加到SaveFileDialogInstance.CustomPlaces集合中。

下面的代码需要一些调整……

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