user11415509
user11415509

Reputation:

Is copying file to USB drive possible in Xamarin.Android?

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?

Upvotes: 2

Views: 853

Answers (1)

Leo Zhu
Leo Zhu

Reputation: 14956

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

Upvotes: 1

Related Questions