简体   繁体   中英

Can I check available storage in the Device on Xamarin Forms?

I am trying to make an app that requires that I frequently send recorded data to a firebase. When network goes out or battery is about to die, I am saving all of the data that wasn't stored into firebase locally. However, to do this I require about 20 MB of data (my data is pretty big). That being said, I want to find a way to check the available storage (and the battery if possible) to give the user a warning. Is this possible using Xamarin Forms? Also, is there a way that I can make this solution universal (ie I don't need a separate piece of code for iOS vs. Android)? (I am new to Xamarin and C#)

Use the following code to check the free size of a device:

For iOS:

NSFileManager.DefaultManager.GetFileSystemAttributes (Environment.GetFolderPath (Environment.SpecialFolder.Personal)).FreeSize;

For Android:

var freeExternalStorage = Android.OS.Environment.ExternalStorageDirectory.UsableSpace;

There is no universal option, but you can wrap it an interface like so and implement it on each project:

public interface IStorage
{
    double GetRemainingStorage();
}

It would be great if a feature like this could be added in Xamarin.Essentials - there was a request on GitHub but it never really made it.

If there are any issues with the code - please tell me.

Hope this helped,

Instructions Create an interface in your shared project titled IStorage .

In your Android project create a class titled AndroidStorageManager (you can name it however you would like). Make it so it extends IStorage . The method GetRemainingStorage() should be of return type double .

在此处输入图像描述

 public class AndroidStorageManager : IStorage
    {
        public double GetRemainingStorage()
        {
            var freeExternalStorage = Android.OS.Environment.ExternalStorageDirectory.UsableSpace;

            return freeExternalStorage;
        }
    }

For iOS Create a class in your iOS project titled iOSStorageManager which extends IStorage :

 public class iOSStorageManager : IStorage
    {
        public double GetRemainingStorage()
        {
            return NSFileManager.DefaultManager.GetFileSystemAttributes(Environment.GetFolderPath(Environment.SpecialFolder.Personal)).FreeSize;
        }
    }

In your Android implementation - add the following code above the namespace:

[assembly: Xamarin.Forms.Dependency(
          typeof(AndroidStorageManager))]

For iOS:

[assembly: Xamarin.Forms.Dependency(
          typeof(iOSStorageManager))]

To get the storage:

 IStorage storageManager = DependencyService.Get<IStorage>();
            double remaining = storageManager.GetRemainingStorage();

Hope this clarified things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM