question

ASH-1598 avatar image
0 Votes"
ASH-1598 asked imagaghfar-7869 commented

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

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>


dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JarvanZhang-MSFT commented

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.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi, @ASH-1598
May I know whether your issue has been solved or not? If not, please share it in here. We can work together to figure it out.

0 Votes 0 ·
HALASDADABDELHAMIDAbdElkarim-2561 avatar image
0 Votes"
HALASDADABDELHAMIDAbdElkarim-2561 answered imagaghfar-7869 commented

yes, to solve

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.