Skip to content

Instantly share code, notes, and snippets.

@kaluznyo
Created February 26, 2021 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaluznyo/db8e5cea3f4c50d45990a5c2bf3cb4d6 to your computer and use it in GitHub Desktop.
Save kaluznyo/db8e5cea3f4c50d45990a5c2bf3cb4d6 to your computer and use it in GitHub Desktop.
# Resources\xml\provider_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="reports" path="Reports" />
</paths>
# Add it to your manifest in application section
<provider android:name="androidx.core.content.FileProvider" android:authorities="ch.xxx.xxxx.provider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
</provider>
# Open file method
public void OpenFile(string filePath)
{
try
{
string extension = Path.GetExtension(filePath);
string application;
switch (extension.ToLower())
{
case ".doc":
case ".docx":
application = "application/msword";
break;
case ".pdf":
application = "application/pdf";
break;
case ".xls":
case ".xlsx":
application = "application/vnd.ms-excel";
break;
case ".jpg":
case ".jpeg":
case ".png":
application = "image/jpeg";
break;
default:
application = "*/*";
break;
}
Java.IO.File file = new(filePath);
file.SetReadable(true);
# Important !
Android.Net.Uri uri = FileProvider.GetUriForFile(Android.App.Application.Context, "ch.xxxx.xxx.provider", file);
Intent intent = new(Intent.ActionView);
intent.SetDataAndType(uri, application);
intent.AddFlags(ActivityFlags.NewTask);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
Android.App.Application.Context.StartActivity(intent);
}
catch (Exception ex)
{
CrossToastPopUp.Current.ShowToastWarning(ex.ToString());
}
}
# Method called to download and open
string filePath = Android.App.Application.Context.GetExternalFilesDir("Reports").AbsolutePath + "/" + filename;
File.WriteAllBytes(filePath, bytes);
OpenFile(filePath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment