In Android 11 trying to download a file and open it with the default application.
The code does work in Android version 9 and 10 and correctly asks user which app they want to open the file with.
I am using xamarin essentials to open the file
var filePath = Path.Combine(FileSystem.AppDataDirectory, $"{result.Replace(" ", "")}.pdf");
using (FileStream linkFile = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
await pdfDoc.CopyToAsync(linkFile);
}
if (File.Exists(filePath))
{
await Launcher.OpenAsync(new OpenFileRequest
{
File = new ReadOnlyFile(filePath)
});
}
Also getting the exact same error when trying to email the file as well with this code
var file = new ReadOnlyFile(filePath);
var emailAttach = new EmailAttachment(file);
email.Attachments.Add(emailAttach);
await Email.ComposeAsync(email);
The Error
Object reference not set to an instance of an object.
at Xamarin.Essentials.FileProvider.IsFileInPublicLocation (System.String filename) [0x0000d] in d:\a\1\s\Xamarin.Essentials\Types\FileProvider.android.cs:92
at Xamarin.Essentials.Platform.GetShareableFileUri (System.String filename) [0x00000] in d:\a\1\s\Xamarin.Essentials\Platform\Platform.android.cs:105
at Xamarin.Essentials.Launcher.PlatformOpenAsync (Xamarin.Essentials.OpenFileRequest request) [0x00000] in d:\a\1\s\Xamarin.Essentials\Launcher\Launcher.android.cs:41
at Xamarin.Essentials.Launcher.OpenAsync (Xamarin.Essentials.OpenFileRequest request) [0x00000] in d:\a\1\s\Xamarin.Essentials\Launcher\Launcher.shared.cs:43
at AppName.Views.JobDetails.GeneratePDF () [0x0034d] in C:\Users\User\source\repos\AppName\AppName\AppName\Views\JobDetails.xaml.cs:416
I have tried using hardcoded paths to a public directory and other helpers for file paths, all with the same error
string fileDir = @"/storage/emulated/0/Android/data/com.*CompanyName*.*AppName*/files/";
string fileDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
(And various other special folders)
string fileDir = FileSystem.CacheDirectory
*Edit
Modified code a little to
var readOnlyFile = new ReadOnlyFile(filePath);
var openFileReq = new OpenFileRequest();
openFileReq.File = readOnlyFile;
await Launcher.OpenAsync(openFileReq);
Error happens on
await Email.ComposeAsync(email);
and
await Launcher.OpenAsync(openFileReq);