Xamarin android save text file

i am using xamarin and i want to save txt file there so i have some script that is saving

    private void SavetoSd()
           {
               var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
               var filePath = System.IO.Path.Combine(sdCardPath, "iootext.txt");
               if (!System.IO.File.Exists(filePath))
               {
                   using(System.IO.StreamWriter write = new System.IO.StreamWriter(filePath,true))
                   {
                       write.Write(etSipServer.ToString());
                   }
               }

           }

but the error is that

System.UnauthorizedAccessException: Access to the path "/mnt/sdcard/iootext.txt" is denied.
any help??

in manifest i have added this

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Tagged:

Answers

  • LearnEverythingLearnEverything ✭✭✭ USMember ✭✭✭
    public async static void  SaveTextAsync(string content, string fileName)
            {
                var backingFile = Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, fileName);
                using (var writer = File.CreateText(backingFile))
                {
                    await writer.WriteAsync(content);
                }
            }
            public async static Task<string> GetTextAsync(string fileName)
            {
                string content = "";
                var backingFile = Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, fileName);
                if (backingFile == null || !File.Exists(backingFile))
                    return content;
                using (var streamReader = new StreamReader(backingFile))
                {
                    content = await streamReader.ReadToEndAsync();
                }
                return content;
            }
    
Sign In or Register to comment.