Downloading and opening file of an unknown mime type

RiskoTuosRiskoTuos USMember
edited June 2016 in Xamarin.Android

I am trying to download and open a file. What I am trying to achieve is to download the file to a local storage and once the download is finished, try to open the file or give user an option to select an App that they wish to open the file in. So far I have this:

 public void GoToViewFile(string fileUrl, string fileName)
 {
     var downloadPath = Path.Combine(Path.GetTempPath(), fileName);
     var webClient = new WebClient();
     var fileUri = new System.Uri(fileUrl);
     webClient.DownloadFileCompleted += WebClientDownloadFileCompleted(downloadPath);
     webClient.DownloadFileAsync(fileUri, downloadPath);
 }

 AsyncCompletedEventHandler WebClientDownloadFileCompleted(string downloadPath)
 {
     Action<object, AsyncCompletedEventArgs> action = (sender, e) =>
     {
         var downloadedFilePath = downloadPath;
         RunOnUiThread(() =>
         {
             var actionView = new Intent(Intent.ActionView );
             actionView.SetData(Uri.Parse(downloadedFilePath));
             StartActivity(actionView);
         });
     };
     return new AsyncCompletedEventHandler(action);
 }

That is not working and I am getting an error:

Android.Content.ActivityNotFoundException: No Activity found to handle Intent

Could you please advise where am I getting it wrong? Thanks

Tagged:

Answers

  • RiskoTuosRiskoTuos USMember

    I needed to pass the right mime type:

    var actionView = new Intent(Intent.ActionView);
    var extension = MimeTypeMap.GetFileExtensionFromUrl(downloadPath);
    var mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
    actionView.SetDataAndType(Uri.Parse(downloadedFilePath), mimeType);
    StartActivity(actionView);
    
  • ThomasMielkeThomasMielke ✭✭ DEMember ✭✭

    Note: GetMimeTypeFromExtension() is case sensitive. I'd recommend this form, in case of a DOSsy file name like IMAGE.JPG:

    MimeTypeMap.Singleton.GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl(uri.Path.ToLower()));

Sign In or Register to comment.