Search code examples
c#xamarin.androidandroid-external-storage

Context.GetExternalFilesDir() is not accepting null


I am trying to get the path to the private external storage directory of my c# xamarin android app. The microsoft docs tell us to use

Android.Content.Context.GetExternalFilesDir(string)

However, when I try to use this function, I get the following error regarding that function:

An object reference is required for the non-static field, method or property

This is my code

class RecorderController {
    string externalStoragePath;

    public RecorderController() {
        externalStoragePath = Path.Combine(Context.GetExternalFilesDir(null), "recordings");
     
     // I have also tried the following:
     // string s = null;
     // externalStoragePath = Path.Combine(Context.GetExternalFilesDir(s), "recordings");

     // Even when I try to get the path to the Downloads folder, I get the same error:
     // string s = Android.OS.Environment.DirectoryDownloads;
     // externalStoragePath = Path.Combine(Context.GetExternalFilesDir(s), "recordings");
    }
}

I have no clue how to solve this, does anybody know what I am doing wrong?


Solution

  • Apparently I had to use an instance of Context, like Mike Christensen commented. I also missed that GetExternalFilesDir returns a File object, and that I should use AbsolutePath after it, like Leo Zhu said.

    I changed my code to

    class RecorderController {
        string externalStoragePath;
    
        public RecorderController(Context con) {
            PermanenteOpslagPad = Path.Combine(con.GetExternalFilesDir(null).AbsolutePath, "recordings"); 
        }
    }