Portable USB device path obtained with shell32 - invalid characters in path

161 views Asked by At

I'm looking for a way to access files on a smartphone connected through USB cable using standard System.IO stuff like Directory and StreamReader.

I have obtained a pretty wicked-looking path to my USB device using this code:

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;
}

Which gets me a path like ::{20D0AAAA-AAAA-AAAA-AAAA-0800AAAAAAAA}\\\?\usb#vid_12d1&pid_107e&mi_00#6&aaaaaaa&0&0000#{6ac2aaaa-aaaa-aaaa-aaaa-f98faaaaaaaa}. I can paste that into the Windows Explorer address bar and it redirects to something like This PC\Samsung\Internal Storage.

Obviously I can't do anything with that path e.g. Directory.GetFiles() because I get InvalidPathException.

How do access files from a path like that?

1

There are 1 answers

2
JanH On

Does this code work for you?

 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");
        }

And than accessing all files in usb

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