External storage in xamarin forms

Recerec78FG 61 Reputation points

Im trying to create an excel file in xamarin forms, populate the file with some user generated data and save that excel file on the user's device so that they can share it with other applications(in my case google drive).

But when I use DirectoryDocuments PRIVATE_EXTERNAL_STORAGE/Documents in exteranl storage, it breaks and says access to path denied.. Ive searched the error multiple times but could not find a solution that worked for me. and yes i have enabled read and write to external storage premissions. Please help me.

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

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 69,386 Reputation points Microsoft Vendor


    Welcome to our Microsoft Q&A platform!

    DirectoryDocuments PRIVATE_EXTERNAL_STORAGE/Documents in exteranl storage,

    Due to the android 11 limitation. you cannot store file to external storage,

    You can try to use string testPath = Android.App.Application.Context.GetExternalFilesDir("").AbsolutePath + $"filename.txt"; path. It will store your file to the package folder


    Here is my demo code to store file.

       string testPath = Android.App.Application.Context.GetExternalFilesDir("").AbsolutePath + $"filename.txt";  
                   using (System.IO.FileStream os = new System.IO.FileStream(testPath, System.IO.FileMode.Create))  
                      var charData = "this is a test text".ToCharArray();  
                     var  byData = new byte[charData.Length];  
                       os.Write(byData,0, byData.Length);  

    Best Regards,

    Leon Lu

    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 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful