Xamarin forms: How to create folder and a file in device external storage?

Sreejith Sree 1,251 Reputation points
2021-03-04T06:20:20.98+00:00

I am trying to create a folder and a text file in that folder on the device's external storage. The same as WhatsApp does. Also, I need to write some data to that file.

Is it possible to do this in xamarin forms? Or should we need to use a dependency service?

Thanks in advance

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

Accepted answer
  1. JarvanZhang 23,936 Reputation points
    2021-03-05T07:38:52.96+00:00

    I tried this but getting System.UnauthorizedAccessException: 'Access to the path "/storage/emulated/0/Download/myfile.txt" is denied

    Hi, @Sreejith Sree . Android 10 introduced a new storage paradigm for apps called scoped storage which changes the way apps store and access files on a device's external storage. If you target Android 10 (API level 29) or higher, set the value of android:requestLegacyExternalStorage to true in your app's manifest file.

    Check the doc: https://developer.android.com/training/data-storage/use-cases#opt-out-scoped-storage

    I need a create a folder first, then a text file on that folder

    You could use File.Exists(xx) to check if the folder exists, and use Directory.CreateDirectory(xx) to create the folder if not. Check the code:

       [assembly: Xamarin.Forms.Dependency(typeof(AccessFileImplement))]  
       namespace TestApplication.Droid  
       {  
           public class AccessFileImplement : IAccessFileService  
           {  
               void IAccessFileService.CreateFile(string FileName)  
               {  
                   string text = "hello world";  
                   byte[] data = Encoding.ASCII.GetBytes(text);  
                   string rootPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);  
                   var filePathDir = Path.Combine(rootPath, "folder");  
                   if (!File.Exists(filePathDir))  
                   {  
                       Directory.CreateDirectory(filePathDir);  
                   }  
                   string filePath = Path.Combine(filePathDir, FileName);  
                   File.WriteAllBytes(filePath, data);  
               }  
           }  
       }  
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. JarvanZhang 23,936 Reputation points
    2021-03-04T08:07:43.1+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    I am trying to create a folder and a text file in that folder on the device's external storage ... should we need to use a dependency service?

    The File class provides the related method to create, delete, and read files in the shared project, but it can only access the application folder.

       File.WriteAllText(fileName, text);  
       string text = File.ReadAllText(fileName);  
    

    To create a file in the external storage, try to achieve the function on the native platform using DependencyService.

       //1.create an interface to define the method  
       public interface IAccessFile  
       {  
           void CreateFile(string FileName);  
       }  
         
       //2.implement the service on the android platform  
       [assembly: Xamarin.Forms.Dependency(typeof(AccessFileImplement))]  
       namespace XamarinFirebase.Droid  
       {  
           public class AccessFileImplement : IAccessFile  
           {  
         
         
               void CreateFile(string FileName)  
               {  
                   string text = "xxx";  
                   byte[] data = Encoding.ASCII.GetBytes(text);  
                   string DownloadsPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);  
                   string filePath = Path.Combine(DownloadsPath, FileName);  
                   File.WriteAllBytes(filePath, data);  
               }  
           }  
       }  
         
       //3.consume the DependencyService command in the shared project  
       DependencyService.Get<IAccessFile>().CreateFile("myfile.txt");  
    

    It cannot be available on iOS platform, iOS imposes some restrictions on what an application can do with the file system to preserve the security of an application’s data.
    An application is limited to reading and writing files within its home directory (installed location); it cannot access another application’s files.

    Related tutorials:
    https://learn.microsoft.com/en-us/xamarin/android/platform/files/external-storage?tabs=windows
    https://learn.microsoft.com/en-us/xamarin/ios/app-fundamentals/file-system#special-considerations

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