Search code examples
xamarinxamarin.formsxamarin.androidxamarin.iosxamarin.uwp

Best way to determine the amount of space available for storing app files with Xamarin forms?


From research I have found that it is possible to determine the available space for storing app files on iOS, Android and UWP using dependency services with the Platform specific code below:

For iOS:

private double GetRemainingStorageSpace(string directoryPath)

{
    
    var freeExternalStorage = NSFileManager.DefaultManager.GetFileSystemAttributes(directoryPath).FreeSize;

    return (double)freeExternalStorage;

}

For Android it can be done like:

var path = new StatFs(directoryPath);
long blockSize = path.BlockSizeLong;

long avaliableBlocks = path.AvailableBlocksLong;

double freeSpace = blockSize * avaliableBlocks;


return freeSpace

or like this:

var fl = new Java.IO.File(directoryPath);

var freeSpace = fl.UsableSpace;
return (double)freeSpace;

For UWP:

string freeSpaceKey = "System.FreeSpace";


StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(directoryPath);

var properties = await folder.Properties.RetrievePropertiesAsync(new string[]
{
freeSpaceKey
});


var freeSpace = properties[freeSpaceKey];


return (UInt64)freeSpace;

My question then is:

1.) Do these lines of code above actually return the amount of bytes that can be stored in a specific directory? Or do they return the amount of bytes that can be stored on the whole device?

2.) For Android I am not too sure what the difference between the two ways of doing this are I am hoping for an explanation of the difference between the both of then and which is a better to use?

Would appreciate an explanation.


Solution

  • 1.) Do these lines of code above actually return the amount of bytes that can be stored in a specific directory? Or do they return the amount of bytes that can be stored on the whole device?

    Obviously it is specific directory ,because in the code it needs specific folder path as parameter .

    You can try to set directoryPath as System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments)

    and

    System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)

    to see the difference.


    2.) For Android I am not too sure what the difference between the two ways of doing this are I am hoping for an explanation of the difference between the both of then and which is a better to use?

    I can't tell the difference or which is better, because based on my test the result comes the same , and for details you can refer to here , it's maybe helpful .