【问题标题】:Portable USB device path obtained with shell32 - invalid characters in path使用 shell32 获得的便携式 USB 设备路径 - 路径中的字符无效
【发布时间】:2023-03-11 11:06:02
【问题描述】:

我正在寻找一种方法来访问通过 USB 电缆连接的智能手机上的文件,该智能手机使用标准的 System.IO 内容,例如 DirectoryStreamReader

我使用以下代码获得了一条通往我的 USB 设备的非常邪恶的路径:

public string GetDevicePath()
{
    dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
    var folder = shell.BrowseForFolder(0, "Select your Android device", 0);
    if (folder == null)
    {
        // user closed the dialog
        return null;
    }
    var fi = (folder as Folder3).Self;
    return fi.Path;
}

这让我得到了一条像::{20D0AAAA-AAAA-AAAA-AAAA-0800AAAAAAAA}\\\?\usb#vid_12d1&pid_107e&mi_00#6&aaaaaaa&0&0000#{6ac2aaaa-aaaa-aaaa-aaaa-f98faaaaaaaa} 这样的路径。我可以将它粘贴到 Windows 资源管理器地址栏中,它会重定向到类似 This PC\Samsung\Internal Storage 的内容。

显然我无法对这条路径做任何事情,例如Directory.GetFiles() 因为我得到了InvalidPathException

如何从这样的路径访问文件?

【问题讨论】:

  • 您应该使用 USB 设备的供应商驱动程序,而不是通用的 Microsoft 驱动程序。我怀疑你得到的字符是由于你使用了错误的 USB 驱动程序。

标签: c# windows path shell32 system.io.directory


【解决方案1】:

这段代码对你有用吗?

 public static string GetUsbPath(string usbLetterOrName) // "F:\" or "YourUsbName"
        {
            DriveInfo[] allDrives = DriveInfo.GetDrives();            
            foreach (DriveInfo d in allDrives)
            {
                if (d.DriveType == DriveType.Removable)
                {
                    if(d.Name == usbLetterOrName || d.VolumeLabel == usbLetterOrName)
                    {
                        return d.RootDirectory.FullName;
                    }
                }
            }
            throw new Exception("Drive not found");
        }

比访问usb中的所有文件

var files = new DirectoryInfo(GetUsbPath("MyUsb")).GetFiles()

【讨论】:

  • 对不起,这对我不起作用。 DriveInfo.GetDrives() 仅获取物理和网络驱动器,例如 C:D:X:。 USB 设备不在此列表中。
  • 该代码获取 USB 闪存驱动器而不是设备……我的错。你可以试试stackoverflow.com/a/60478286/10092614
猜你喜欢
  • 2011-01-29
  • 2017-02-21
  • 1970-01-01
  • 2023-04-01
  • 2013-10-07
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
  • 2012-05-31
相关资源
最近更新 更多