Display and Download File PDF base64 binary in Android #XAMARIN.FORMS

AS_H 41 Reputation points
2021-07-01T08:23:39.733+00:00

Help me guys
I have tow error
1- #exception Access to the path "/storage/emulated/0/Download/
.PDF" is denied.

  • in this line -- File.WriteAllBytes(filePath, bytes);
    2- #exception file exposed beyond app through intent.getdata()
  • in this line -- Xamarin.Forms.Forms.Context.StartActivity(intent);**

this is code:

[assembly: Xamarin.Forms.Dependency(typeof(SaveFile))]
namespace **
{
class SaveFile : ISaveFile
{
public async Task SaveFiles(string filename, byte[] bytes)
{
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
string filePath = Path.Combine(documentsPath, filename);

        // check strorage permission   
        if (ContextCompat.CheckSelfPermission(Xamarin.Forms.Forms.Context, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)  
        {  
            GetStoragePermisson();  

        }  
        else  
        {  
            File.WriteAllBytes(filePath, bytes);  
            await OpenFileAsync(filePath, filename);  
        }  
    }  
    public async Task OpenFileAsync(string filePath, string filename)  
    {  

        byte[] bytes = File.ReadAllBytes(filePath);  

        //Copy the private file's data to the EXTERNAL PUBLIC location  
        string externalStorageState = global::Android.OS.Environment.ExternalStorageState;  
        string application = "";  

        string extension = System.IO.Path.GetExtension(filePath);  
        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 pathFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);  
        string absolutePath = pathFile.AbsolutePath + "/" + filename;  
     
        try  
        {  
            File.WriteAllBytes(absolutePath, bytes);  
    }  
        catch (Exception e)  
        {  
            Console.WriteLine(e.Message + "");  
            Toast.MakeText(Android.App.Application.Context, "", ToastLength.Short).Show();  
}  


Java.IO.File file = new Java.IO.File(absolutePath);  
        file.SetReadable(true);  
         
        Android.Net.Uri uri = Android.Net.Uri.FromFile(file);  
         
        Intent intent = new Intent(Intent.ActionView);  
        intent.SetDataAndType(uri, application);  
        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask | ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask);  

         
              
        try  
        {  
            Xamarin.Forms.Forms.Context.StartActivity(intent);  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine(e.Message + "");  
            Toast.MakeText(Android.App.Application.Context, "", ToastLength.Short).Show();  
        }  


    }  

    //Request Storage permision    
    public void GetStoragePermisson()  
    {  
        var activity = Xamarin.Forms.Forms.Context as MainActivity;  
        try  
        {  
            ActivityCompat.RequestPermissions(activity, new string[] { Manifest.Permission.WriteExternalStorage }, 1);  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine(e.Message + "");  
            Toast.MakeText(Android.App.Application.Context, "", ToastLength.Short).Show();  
        }  

    }  

-----------
add permission to android manifest------------
</manifest>
.
.
<application>
.
.
.
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider" android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@XML /file_paths" />
</provider>

</application>  

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
</manifest>

-----------
create file_paths.xml in folder xml------------

<?xml version="1.0" encoding="UTF-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Pictures" />
<external-files-path name="my_movies" path="Movies" />
<external-path name="external_files" path="."/>

</paths>

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,292 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. JarvanZhang 23,936 Reputation points
    2021-07-02T06:34:41.337+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    exception Access to the path "/storage/emulated/0/Download/.PDF" is denied

    Do you still encounter the issue? To access the external storage on Android, we need to request the storage permission at runtime which you've achieve in your code. I tested the 'SaveFiles' method in my sample, it works well.

    exception file exposed beyond app through intent.getdata()

    Since Android Api 24, we have to use FileProvider class to give access to the particular file. Try to change the uri as below:

       var context = MainActivity.Instance; //you could create a static instance of MainActivity class to obtains the context in other classes  
         
       //Android.Net.Uri uri = Android.Net.Uri.FromFile(file);  
       var uri = FileProvider.GetUriForFile(context , context .PackageName + ".fileprovider", file);   
         
       Intent intent = new Intent(Intent.ActionView);  
       intent.SetDataAndType(uri, "image/*");  
       intent.SetFlags(ActivityFlags.NewTask);  
       intent.SetFlags(ActivityFlags.GrantReadUriPermission);  
       intent.SetFlags(ActivityFlags.ClearWhenTaskReset);  
         
       context.StartActivity(intent);  
         
       //MainActivity class  
       public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity  
       {  
           public static MainActivity Instance { get; set; }  
           protected override void OnCreate(Bundle savedInstanceState)  
           {  
               base.OnCreate(savedInstanceState);  
               Instance = this;  
               ...  
           }  
       }  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. 2021-07-18T21:06:27.29+00:00

    yes, to solve

    0 comments No comments