【发布时间】:2010-11-10 14:26:09
【问题描述】:
我想在 c# 中获取可移动磁盘的列表。我想跳过本地驱动器。 因为我希望用户只将文件保存在可移动磁盘中。
【问题讨论】:
标签: c# .net removable-storage driveinfo
我想在 c# 中获取可移动磁盘的列表。我想跳过本地驱动器。 因为我希望用户只将文件保存在可移动磁盘中。
【问题讨论】:
标签: c# .net removable-storage driveinfo
此方法需要参考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);
已添加
至于保存部分,据我所知,我认为您不能限制允许用户保存的位置以使用 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();
【讨论】:
DriveInfo.GetDrives() 更可靠的方法,并且依赖于IsRemovable 属性:插入USB 端口的硬盘可能不会被识别为IsRemovable所以很容易错过。使用 WMI 需要更多的工作,但更健壮。