External storage in xamarin forms

Recerec78FG 61 Reputation points
2021-07-08T21:28:18.837+00:00

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.

Xamarin
Xamarin
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
    2021-07-09T05:53:22.9+00:00

    Hello,​

    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

    113203-image.png

    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);  
                       os.Close();  
                   }  
    

    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