How do I get the downloaded file name?

MikeRowley403MikeRowley403 CAMember ✭✭✭

I have my app downloading a file using the DownloadManager, however if I take the pointer from the Enqueue method and pass it to GetUriForDownloadedFile I always get a null however the file downloads every time.

I need the downloaded file name as it may not always match the filename on the server as the DownloadManager appends a -# on the file if duplicates are downloaded. Any suggestions on how to get the downloaded file name so that I can pass it to a Send Intent?


            Android.Net.Uri contentUri = Android.Net.Uri.Parse(uri);
            Android.App.DownloadManager.Request r = new Android.App.DownloadManager.Request(contentUri);
            r.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, filename);
            Android.App.DownloadManager dm = (Android.App.DownloadManager)Xamarin.Forms.Forms.Context.GetSystemService(Android.Content.Context.DownloadService);
            var savedFile = dm.GetUriForDownloadedFile(dm.Enqueue(r));


  • MikeRowley403MikeRowley403 CAMember ✭✭✭

    As is common with Xamarin Forums, I am answering my own question.
    The solution is a bit convoluted, it appears you cannot get the URI for a downloaded file until the DownloadManager is done with the download. I solved my issue by catching the completed download in a BroadcastReceiver. DownloadIDsToShare is a List to ensure I don't fire the share intent on every downloaded file but only those where the user has clicked the Share Button.

        [IntentFilter(new[] { DownloadManager.ActionDownloadComplete })]
        class BootCompletedBroadcastMessageReceiver : BroadcastReceiver
            public override void OnReceive(Context context, Intent intent)
                long dwnId = intent.GetLongExtra(DownloadManager.ExtraDownloadId, 0);
                if (MainActivity.CurrentActivity.DownloadIDsToShare.Contains(dwnId))
                    Android.App.DownloadManager dm = (Android.App.DownloadManager)Xamarin.Forms.Forms.Context.GetSystemService(Android.Content.Context.DownloadService);
                    var fileURI = dm.GetUriForDownloadedFile(dwnId);
                    var shareFile = new ShareFileService();
  • SirAndriySirAndriy USMember ✭✭✭

    good job @MikeRowley403!!!

  • PeerlessProgrammerPeerlessProgrammer USUniversity ✭✭

    Very helpful @MikeRowley403

    For others that would like more help I found a book through hours of searching that had a good explanation.
    Xamarin Mobile Development for Android Cookbook!

    Hope that helps others that may be struggling.

Sign In or Register to comment.