2

How do I programmatically transfer files from the internal storage of a phone to a USB drive? I don't get the required code to get the external directory.

string pathToDirectory = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath);

The above-posted code gets only the SD card location. How to get access to the USB drive?

jkdev
  • 11,360
  • 15
  • 54
  • 77
  • Related questions: https://stackoverflow.com/q/56209650/3345375 and https://stackoverflow.com/q/55127363/3345375 and https://stackoverflow.com/q/49645503/3345375 – jkdev Aug 28 '19 at 12:03
  • @jkdev Thanks for info .but I would like to know how to share the file to usbdrive using Android USB MANAGER. –  Aug 28 '19 at 12:17
  • [OTG USB Manager - File Manager For Android](https://play.google.com/store/apps/details?id=com.safari.usbtootgconvertor.app&hl=en_US) Is this what you're referring to? – jkdev Aug 28 '19 at 12:27
  • NO iM Mentioned android https://developer.android.com/reference/android/hardware/usb/UsbManager –  Aug 28 '19 at 12:31
  • does it work now ? – Leo Zhu Sep 02 '19 at 03:08
  • not tested @LeoZhu-MSFT –  Sep 03 '19 at 07:04

1 Answers1

1

How to get access to the USB drive?

you could regist broadcast for plug and pull of external storage devices:

Intent.ACTION_MEDIA_MOUNTED 
Intent.ACTION_MEDIA_REMOVED 

UsbReceiver:

class USBReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            string action = intent.Action;
            if (action.Equals(Intent.ActionMediaMounted))
            {
                string mountPath = intent.Data.Path;
            }
        }
    }

Code Snippet:

UsbManager manager = (UsbManager)_mainActivity.GetSystemService(Context.UsbService);
var deviceList = manager.DeviceList;
IEnumerable<UsbDevice> deviceIterator = deviceList.Values.AsEnumerable();

if (deviceIterator.Count() > 0)
  {
    var device = deviceIterator.ElementAt(0);

    ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    var mPermissionIntent = PendingIntent.GetBroadcast(_mainActivity.ApplicationContext, 0, new Intent(ACTION_USB_PERMISSION), 0);

    UsbManager mUsbManager = (UsbManager)_mainActivity.GetSystemService(Context.UsbService);
    mUsbManager.RequestPermission(device, mPermissionIntent);

    bool perm = mUsbManager.HasPermission(device);
    if (perm)
      {
       //File Copy
       File.Copy(FileNameSource, FileNameDestination);
      }
 }
Leo Zhu
  • 15,726
  • 1
  • 7
  • 23
  • Zhu - How do you determine FileNameDestination? I receive a Access Denied exception if I use the direct mount path. – Matt Wise Nov 10 '20 at 01:04