Working with disk space info in forms.

shtpavelshtpavel UAMember

Hello guys!
Is there any forms library that allows us to work with disc space stats? Like available disk space, used disk space etc.

Thanks!

Posts

  • fernandopfernandop USMember ✭✭
    edited June 2015

    Hi, I need the same, if you find any help, please tell me, thanks!

  • shtpavelshtpavel UAMember

    @fernandop You just need to implement it separately and resolve via DependencyService.

  • fernandopfernandop USMember ✭✭

    Ok, thanks, I already implemented it for Android side (if you need the code just tell me).

  • JohnHardmanJohnHardman GBUniversity ✭✭✭✭✭

    @fernandop - Yes please. This is something I will want to add to the support section of my app, for all supported XF platforms.

  • fernandopfernandop USMember ✭✭

    Here you go:

    `

    public class DeviceInformation
    {
        /// <summary>
        /// Current battery level 0 - 100
        /// </summary>
        public int BatteryRemainingChargePercent { get; set; }
        /// <summary>
        /// Current battery status like Charging, Discharging, etc.
        /// </summary>
        public string BatteryStatus { get; set; }
        /// <summary>
        /// Available RAM memory (in bytes).
        /// </summary>
        public long AvailableMainMemory { get; set; }
        /// <summary>
        /// Total RAM memory (in bytes).
        /// </summary>
        public long TotalMainMemory { get; set; }
        /// <summary>
        /// If <c>true</c> indicates that the system is low in memory.
        /// </summary>
        public bool IsLowMainMemory { get; set; }
        /// <summary>
        /// Total size (in bytes) of the internal storage.
        /// </summary>
        public long TotalInternalStorage { get; set; }
        /// <summary>
        /// Free size (in bytes) in the internal storage.
        /// It might be different than available size.
        /// </summary>
        public long FreeInternalStorage { get; set; }
        /// <summary>
        /// Available size (in bytes) in the internal storage.
        /// It might be different than free size.
        /// </summary>
        public long AvailableInternalStorage { get; set; }
        /// <summary>
        /// If <c>true</c> indicates that the device has a removable storage.
        /// </summary>
        public bool HasRemovableExternalStorage { get; set; }
        /// <summary>
        /// If <c>true</c> indicates that the app can write in the removable storage.
        /// </summary>
        public bool CanWriteRemovableExternalStorage { get; set; }
        /// <summary>
        /// Total size (in bytes) of the removable external storage.
        /// </summary>
        public long TotalRemovableExternalStorage { get; set; }
        /// <summary>
        /// Available size (in bytes) of the removable external storage.
        /// </summary>
        public long AvailableRemovableExternalStorage { get; set; }
        /// <summary>
        /// Free size (in bytes) of the removable external storage.
        /// </summary>
        public long FreeRemovableExternalStorage { get; set; }
    
    }
    

    public async Task GetDeviceInformation()
    {
    DeviceInformation devInfo = new DeviceInformation ();

            //* Gets the main memory (RAM) information.
            var activityManager = (ActivityManager)Forms.Context.GetSystemService(Context.ActivityService);
    
            ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
            activityManager.GetMemoryInfo(memInfo);
    
            System.Diagnostics.Debug.WriteLine ("GetDeviceInfo - Avail {0} - {1} MB", memInfo.AvailMem, memInfo.AvailMem / 1024 / 1024);
            System.Diagnostics.Debug.WriteLine ("GetDeviceInfo - Low {0}", memInfo.LowMemory);
            System.Diagnostics.Debug.WriteLine ("GetDeviceInfo - Total {0} - {1} MB", memInfo.TotalMem, memInfo.TotalMem / 1024 / 1024);
    
            devInfo.AvailableMainMemory = memInfo.AvailMem;
            devInfo.IsLowMainMemory = memInfo.LowMemory;
            devInfo.TotalMainMemory = memInfo.TotalMem;
    
            //* Gets the internal storage information.
            StorageInfo internalStorageInfo = this.GetStorageInformation(Environment.GetExternalStoragePublicDirectory("").ToString());
    
            devInfo.TotalInternalStorage = internalStorageInfo.TotalSpace;
            devInfo.AvailableInternalStorage = internalStorageInfo.AvailableSpace;
            devInfo.FreeInternalStorage = internalStorageInfo.FreeSpace;
    
            string extStorage = await this.RemovableStoragePath();
    
            devInfo.HasRemovableExternalStorage = !String.IsNullOrEmpty(extStorage);
    
            if (devInfo.HasRemovableExternalStorage) {
                bool canWrite = await this.IsWriteable (extStorage);
                devInfo.CanWriteRemovableExternalStorage = canWrite;
    
                //* Gets the external removable storage information.
                StorageInfo removableStorageInfo = this.GetStorageInformation(Environment.GetExternalStoragePublicDirectory("").ToString());
                devInfo.TotalRemovableExternalStorage = removableStorageInfo.TotalSpace;
                devInfo.FreeRemovableExternalStorage = removableStorageInfo.FreeSpace;
                devInfo.AvailableRemovableExternalStorage = removableStorageInfo.AvailableSpace;
    
            } else {
                devInfo.CanWriteRemovableExternalStorage = false;
                devInfo.TotalRemovableExternalStorage = 0;
                devInfo.FreeRemovableExternalStorage = 0;
                devInfo.AvailableRemovableExternalStorage = 0;
            }
            return devInfo;
        }
    
        protected StorageInfo GetStorageInformation (string path)
        {
            StorageInfo storageInfo = new StorageInfo();
    
            StatFs stat = new StatFs(path); //"/storage/sdcard1"
            long totalSpaceBytes = 0;
            long freeSpaceBytes = 0;
            long availableSpaceBytes = 0;
    
            /*
              We have to do the check for the Android version, because the OS calls being made have been deprecated for older versions. 
              The ‘old style’, pre Android level 18 didn’t use the Long suffixes, so if you try and call use those on 
              anything below Android 4.3, it’ll crash on you, telling you that that those methods are unavailable. 
              http://blog.wislon.io/posts/2014/09/28/xamarin-and-android-how-to-use-your-external-removable-sd-card/
             */
            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr2) {
                long blockSize = stat.BlockSizeLong;
                totalSpaceBytes = stat.BlockCountLong * stat.BlockSizeLong;
                availableSpaceBytes = stat.AvailableBlocksLong * stat.BlockSizeLong;
                freeSpaceBytes = stat.FreeBlocksLong * stat.BlockSizeLong;
            } else {
    
                totalSpaceBytes = (long)stat.BlockCount * (long)stat.BlockSize;
                availableSpaceBytes = (long)stat.AvailableBlocks * (long)stat.BlockSize;
                freeSpaceBytes = (long)stat.FreeBlocks * (long)stat.BlockSize;
            }
    
            storageInfo.TotalSpace = totalSpaceBytes;
            storageInfo.AvailableSpace = availableSpaceBytes;
            storageInfo.FreeSpace = freeSpaceBytes;
            return storageInfo;
    
        }
    
        private Task<string> RemovableStoragePath() {
            return Task.Run (() => {
                //* Tries to detect if there is a removable storage.
                //* http://blog.wislon.io/posts/2014/09/28/xamarin-and-android-how-to-use-your-external-removable-sd-card/
                string procMounts = System.IO.File.ReadAllText("/proc/mounts");
                System.Diagnostics.Debug.WriteLine("begin /proc/mounts");
                System.Diagnostics.Debug.WriteLine(procMounts);
                System.Diagnostics.Debug.WriteLine("end /proc/mounts");
                var candidateProcMountEntries = procMounts.Split('\n', '\r').ToList();
                candidateProcMountEntries.RemoveAll(s => s.IndexOf("storage", StringComparison.OrdinalIgnoreCase) < 0);
                var bestCandidate = candidateProcMountEntries
                    .FirstOrDefault(s => s.IndexOf("ext", StringComparison.OrdinalIgnoreCase) >= 0
                        && s.IndexOf("sd", StringComparison.OrdinalIgnoreCase) >= 0
                        && s.IndexOf("vfat", StringComparison.OrdinalIgnoreCase) >= 0);
    
                // e.g. /dev/block/vold/179:9 /storage/extSdCard vfat rw,dirsync,nosuid, blah
                if (!string.IsNullOrWhiteSpace(bestCandidate))
                {
                    var sdCardEntries = bestCandidate.Split(' ');
                    var sdCardEntry = sdCardEntries.FirstOrDefault(s => s.IndexOf("/storage/", System.StringComparison.OrdinalIgnoreCase) >= 0);
                    System.Diagnostics.Debug.WriteLine ("It has removable storage {0}", !string.IsNullOrWhiteSpace(sdCardEntry) ? string.Format("{0}", sdCardEntry) : string.Empty);
                    return !string.IsNullOrWhiteSpace(sdCardEntry) ? string.Format("{0}", sdCardEntry) : string.Empty;
                 }
                return string.Empty;
                });
        }
    
        private Task<bool> IsWriteable(string path)
        {
    
            return Task.Run (() => {
                bool result = false;
                try {
    
                    const string someTestText = "some test text";
                    string testFile = string.Format ("{0}/{1}.txt", path, Guid.NewGuid ());
                    System.IO.File.WriteAllText (testFile, someTestText);
                    System.IO.File.Delete (testFile);
                    result = true;
                } catch (Exception ex) { // it's not writeable
                    System.Diagnostics.Debug.WriteLine("ExternalSDStorageHelper", string.Format("Exception: {0}\r\nMessage: {1}\r\nStack Trace: {2}", ex, ex.Message, ex.StackTrace));
                }
    
                return result;
            });
        }`
    
  • fernandopfernandop USMember ✭✭

    @JohnHardman I just posted it, as I said I only did the Android side if you have other platforms I will accept you code! =)

  • JohnHardmanJohnHardman GBUniversity ✭✭✭✭✭

    @fernandop - many thanks. It is on my backlog of things to do, but it's quite a long way down the list. I will post the code when I get to it, but it's likely to be 3-4 months away. Thanks again.

  • fernandopfernandop USMember ✭✭

    It is fine for me, at this moment the app works only for Android devices but would be good to add support for Win and iOS, I will work on that maybe on the end of the year. "De nada" (you are welcome)

  • I need to get these information by using xamarin.forms..is it possible to get it?

  • LearnEverythingLearnEverything USMember ✭✭

    //UWP

    using MasterDetailTemplate.Core.ISpecifics;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.ApplicationModel;
    using Windows.Security.ExchangeActiveSyncProvisioning;
    using Windows.Storage;
    using Windows.System.Profile;
    [assembly: Xamarin.Forms.Dependency(typeof(SystemInfo))]
    namespace MasterDetailTemplate.UWP.Specifics
    {
        public  class SystemInfo : ISystemInfo
        {
            Package package = Package.Current;
            EasClientDeviceInformation eas = new EasClientDeviceInformation();
            public  string SystemFamily
            {
                get
                {
                    AnalyticsVersionInfo ai = AnalyticsInfo.VersionInfo;
                    return ai.DeviceFamily;
                }
            }
            public  string SystemVersion
            {
                get
                {
                    string sv = AnalyticsInfo.VersionInfo.DeviceFamilyVersion;
                    ulong v = ulong.Parse(sv);
                    ulong v1 = (v & 0xFFFF000000000000L) >> 48;
                    ulong v2 = (v & 0x0000FFFF00000000L) >> 32;
                    ulong v3 = (v & 0x00000000FFFF0000L) >> 16;
                    ulong v4 = (v & 0x000000000000FFFFL);
                    return $"{v1}.{v2}.{v3}.{v4}";
                }
            }
            public  string SystemArchitecture { get { return package.Id.Architecture.ToString(); } }
            public  string ApplicationName { get { return package.DisplayName; } }
            public  string ApplicationVersion
            {
                get
                {
                    PackageVersion pv = package.Id.Version;
                    return $"{pv.Major}.{pv.Minor}.{pv.Build}.{pv.Revision}";
                }
            }
            public  string DeviceManufacturer { get { return eas.SystemManufacturer; } }
            public  string DeviceModel { get { return eas.SystemProductName; } }
            public string DeviceType
            {
                get
                {
                    var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues;
                    return (qualifiers.ContainsKey("DeviceFamily") && qualifiers["DeviceFamily"] == "Mobile") ? "Mobile" : "Tablet";
                }
            }
            public async Task<string> FreeSpace()
            {
                var folder = ApplicationData.Current.LocalFolder;
                var retrivedProperties = await folder.Properties.RetrievePropertiesAsync(new string[] { "System.FreeSpace" });
                var folderSize = (UInt64)retrivedProperties["System.FreeSpace"];
                var KBSize = folderSize / 1024.0;
                return KBSize.ToString();
            }
        }
    }
    
Sign In or Register to comment.