如何判断所选路径来自USB或网络驱动器?UWP(及WinRT)能否检测存储类型?
嘿,我来帮你拆解这两个问题的解决方案,都是我做Windows开发时常用的实操思路:
判断指定路径是USB/网络驱动器(常规桌面程序)
对于普通的Windows桌面应用(比如WPF、WinForms),可以借助.NET的DriveInfo类快速判断,步骤很清晰:
- 第一步:提取路径的根目录:用
Path.GetPathRoot()把目标路径转换成驱动器根路径(比如C:\、D:\),因为DriveInfo需要基于根路径初始化。 - 判断USB驱动器:检查
DriveInfo.DriveType是否等于DriveType.Removable。这个枚举值会识别绝大多数USB闪存盘、移动硬盘,不过要注意部分读卡器也可能被标记为Removable,如果需要更精准的设备识别,可能要结合WMI查询硬件ID,但常规场景下DriveType.Removable足够用。 - 判断网络驱动器:检查
DriveInfo.DriveType是否等于DriveType.Network,这个能直接识别映射到本地的网络盘符。
给你个C#代码示例,直接就能用:
using System.IO; public static bool IsUsbDrive(string filePath) { string rootPath = Path.GetPathRoot(filePath); if (string.IsNullOrEmpty(rootPath)) return false; try { DriveInfo driveInfo = new DriveInfo(rootPath); return driveInfo.DriveType == DriveType.Removable; } catch (IOException) { // 路径无效、无访问权限时返回false return false; } } public static bool IsNetworkDrive(string filePath) { string rootPath = Path.GetPathRoot(filePath); if (string.IsNullOrEmpty(rootPath)) return false; try { DriveInfo driveInfo = new DriveInfo(rootPath); return driveInfo.DriveType == DriveType.Network; } catch (IOException) { return false; } }
UWP/WinRT框架下检测文件/文件夹位置
UWP有沙箱权限限制,不能直接像桌面程序那样访问驱动器根目录,但通过文件选择器获取的StorageFile/StorageFolder实例,我们可以通过属性查询来判断位置类型:
- 核心思路是:先找到文件/文件夹所在的根文件夹,然后查询根文件夹的
System.DriveType属性,通过属性值判断是可移动存储还是网络存储。 - 注意:只有用户通过
FileOpenPicker/FolderPicker主动授权的文件/文件夹,你才能访问这些属性,否则会触发权限异常。
下面是对应的UWP代码示例:
using Windows.Storage; using Windows.Storage.FileProperties; public static async Task<bool> IsRemovableStorageAsync(StorageFile file) { // 递归获取文件所在的根文件夹 StorageFolder rootFolder = await file.GetParentAsync(); while (rootFolder != null && await rootFolder.GetParentAsync() != null) { rootFolder = await rootFolder.GetParentAsync(); } if (rootFolder == null) return false; // 检索驱动器类型属性(枚举值:2=Removable,4=Network) var properties = await rootFolder.Properties.RetrievePropertiesAsync(new[] { "System.DriveType" }); if (properties.TryGetValue("System.DriveType", out object driveTypeObj) && driveTypeObj is int driveType) { return driveType == 2; } return false; } public static async Task<bool> IsNetworkStorageAsync(StorageFile file) { StorageFolder rootFolder = await file.GetParentAsync(); while (rootFolder != null && await rootFolder.GetParentAsync() != null) { rootFolder = await rootFolder.GetParentAsync(); } if (rootFolder == null) return false; var properties = await rootFolder.Properties.RetrievePropertiesAsync(new[] { "System.DriveType" }); if (properties.TryGetValue("System.DriveType", out object driveTypeObj) && driveTypeObj is int driveType) { return driveType == 4; } return false; }
额外补充:如果需要识别OneDrive这类云存储位置,可以查询System.FileLocation属性,云存储对应的属性值通常是Cloud。
内容的提问来源于stack exchange,提问作者i84
相关产品推荐
相关产品推荐

