0

I'm trying to create a folder accessible to anyone. When i try to get the directory of External Storage with

var path= Android.OS.Environment.ExternalStorageDirectory.ToString();

i see the error:

Android does not contain a definition for 'OS'.

Can anyone help me?

Thanks.

  • try to shake your bundle: `Step 1. Project > Update NugetPackages Step 2. Build > Clean All Step 3. Build > Build All` – Sergio Belevskij Mar 08 '20 at 13:17
  • Thanks, but that doesn't work. Could it be because of my type of project? My project is Android -> Android Xaml App. – bronckhorst Mar 08 '20 at 15:44
  • It look like the problem is with the type of my project. My project is Android XAML App (Xamarin Forms). The namespace Android.OS is only available in projects Android App (Xamarin). Is there a way to resolve that? – bronckhorst Mar 08 '20 at 19:48

2 Answers2

0

It look like the problem is with the type of my project. My project is Android XAML App (Xamarin Forms). The namespace Android.OS is only available in projects Android App (Xamarin). Is there a way to resolve that?

You could create a dependency service to obtain it on Forms.

Xamarin.Forms DependencyService Introduction:

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction

Create the interface:

 public interface IDpendencyService
{
    string GetExternalStorage();
}

The implementation on the Android project could be like this:

public class DependencyImplementation : IDpendencyService
{
    public string GetExternalStorage()
    {
        var path = Android.OS.Environment.ExternalStorageDirectory.ToString();
        return path;
    }
}

Do not forget to register in MainActivity.cs:

Xamarin.Forms.DependencyService.Register<IDpendencyService, DependencyImplementation>();

Usage in Xamarin.forms:

  private void Button_Clicked(object sender, EventArgs e)
    {
        var path = DependencyService.Get<IDpendencyService>().GetExternalStorage();
    }
Wendy Zang - MSFT
  • 10,509
  • 1
  • 7
  • 17
0

In Xamarin.Forms, iOS and Android. you can do it like:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

If you want to get a TempFolder where you can store a temporary cache:

Path.GetTempPath()

Note that if you're accessing to external storage, you might need to have some permissions in Android manifest file

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

There are already some great answer for this which explain in more details: What is the best Environment.SpecialFolder for store application data in Xamarin.Forms?

Huy.Vu
  • 173
  • 10