compound
compound

Reputation: 41

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?

Upvotes: 3

Views: 1279

Answers (2)

compound
compound

Reputation: 41

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"); 
    }
}

Upvotes: 1

Leo Zhu
Leo Zhu

Reputation: 15031

Try to change

externalStoragePath = Path.Combine(Context.GetExternalFilesDir(null), "recordings");

to

externalStoragePath = Path.Combine(GetExternalFilesDir(null).AbsolutePath, "recordings");

Upvotes: 1

Related Questions