• 1
name Punditsdkoslkdosdkoskdo

Xamarin android save text files

I am using Xamarin.Android and I want to save a .txt file to the SD card. Here is the code that I am using:

  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))

However, I receive the following error:

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

I have added the following to the manifest:

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

How can I fix the error?


If you're on Android 6.0+ you will need to perform a runtime check for permissions. This can be done like so:

if ((CheckSelfPermission(Permission.ReadExternalStorage) == (int)Permission.Granted) && 
    (CheckSelfPermission(Permission.WriteExternalStorage) == (int)Permission.Granted))
  • 0
Reply Report