如何在c#中获取可移动磁盘列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1124463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the list of removable disk in c#?
提问by Anuya
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.
我想在 c# 中获取可移动磁盘列表。我想跳过本地驱动器。因为我希望用户只将文件保存在可移动磁盘中。
采纳答案by Lloyd Powell
You will need to reference System.IO
for this method.
您需要参考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
}
}
Or for the LINQ fans:
或者对于 LINQ 粉丝:
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.
添加
至于保存部分,据我所知,我认为您不能限制允许用户保存的位置使用 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");
}
}
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
希望这可以帮助
回答by Rhys Jones
This article looks to do the trick:
这篇文章看起来可以解决问题:
http://zayko.net/post/How-to-get-list-of-removable-drives-installed-on-a-computer-(C).aspx
http://zayko.net/post/How-to-get-list-of-removable-drives-installed-on-a-computer-(C).aspx
回答by Matt Hamilton
How about:
怎么样:
var removableDrives = from d in System.IO.DriveInfo.GetDrives()
where d.DriveType == DriveType.Removable;
回答by S M Kamran
You can also use WMI to get the list of removable drives.
您还可以使用 WMI 获取可移动驱动器列表。
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.
获得驱动器列表后,获取 GUID 并将它们添加到 SaveFileDialogInstance.CustomPlaces 集合。
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();