Example #1
0
        /// <summary>
        /// Uses the Linux Android.OS.StatFS wrapper call to try and see how many blocks are
        /// free/used/available. Results are returned in bytes.
        /// </summary>
        /// <param name="path">The path to use for the basis of the size check</param>
        /// <returns># of bytes free if successful, 0 if none</returns>
        public static FileSystemBlockInfo GetFileSystemBlockInfo(string path)
        {
            var statFs = new StatFs(path);
            var fsbi   = new FileSystemBlockInfo();

            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBeanMr2)
            {
                fsbi.Path               = path;
                fsbi.BlockSizeBytes     = statFs.BlockSizeLong;
                fsbi.TotalSizeBytes     = statFs.BlockCountLong * statFs.BlockSizeLong;
                fsbi.AvailableSizeBytes = statFs.AvailableBlocksLong * statFs.BlockSizeLong;
                fsbi.FreeSizeBytes      = statFs.FreeBlocksLong * statFs.BlockSizeLong;
            }
            else // this was deprecated in API level 18 (Android 4.3), so if your device is below level 18, this is what will be used instead.
            {
                fsbi.Path = path;
                // disable warning about obsoletes, since earlier versions of Android are using the deprecated versions
                // ReSharper disable CSharpWarnings::CS0618
                fsbi.BlockSizeBytes     = (long)statFs.BlockSize;
                fsbi.TotalSizeBytes     = (long)statFs.BlockCount * (long)statFs.BlockSize;
                fsbi.FreeSizeBytes      = (long)statFs.FreeBlocks * (long)statFs.BlockSize;
                fsbi.AvailableSizeBytes = (long)statFs.AvailableBlocks * (long)statFs.BlockSize;
                // ReSharper restore CSharpWarnings::CS0618
            }
            return(fsbi);
        }
        public static long GetFreeSpace(string path)
        {
            StatFs stat      = new StatFs(path);
            long   availSize = (long)stat.AvailableBlocks * (long)stat.BlockSize;

            return(availSize);
        }
Example #3
0
        public long GetAvailableExternalStorageSpace()
        {
            StatFs statFs = new StatFs(ExternalStoragePath);
            long   free   = statFs.AvailableBlocksLong * statFs.BlockSizeLong;

            return(free);
        }
        private static void InitDrive(AndroidDrive drive, int dashesIncludeInName)
        {
            drive.Name = drive.AppFolderPath;
            var c = 0;
            var i = 0;

            for (i = 0; i < drive.Name.Length; i++) // extract '/data/user'
            {
                if (drive.Name[i] == '/')
                {
                    c++;
                }
                if (c == dashesIncludeInName)
                {
                    break;
                }
            }

            if (i < drive.Name.Length)
            {
                drive.Name = drive.Name.Substring(0, i);
            }

            var stats = new StatFs(drive.AppFolderPath);

            drive.BytesFree  = stats.AvailableBlocksLong * stats.BlockSizeLong;
            drive.TotalBytes = stats.BlockCountLong * stats.BlockSizeLong;
        }
Example #5
0
        private void GetSizes(string path)
        {
            StatFs stat = new StatFs(path);

            _freeSpace  = stat.AvailableBytes;
            _totalSpace = stat.TotalBytes;
        }
Example #6
0
        public long GetTotalFileSystemSizeInBytes(string rootPath)
        {
            StatFs stat      = new StatFs(rootPath);
            long   blockSize = stat.BlockSizeLong;
            long   blocks    = stat.BlockCountLong;

            return(blocks * blockSize);
        }
Example #7
0
        public long GetAvailableStorageSpace()
        {
            string root   = FileSystem.Current.LocalStorage.Path;
            StatFs statFs = new StatFs(root);
            long   free   = statFs.AvailableBlocksLong * statFs.BlockSizeLong;

            return(free);
        }
Example #8
0
        public long GetAvailableFileSystemSizeInBytes(string rootPath)
        {
            StatFs stat            = new StatFs(rootPath);
            long   blockSize       = stat.BlockSizeLong;
            long   availableBlocks = stat.AvailableBlocksLong;

            return(availableBlocks * blockSize);
        }
Example #9
0
            /// <summary>
            /// liefert die akt. Daten des Volumes (API level 24 / Nougat / 7.0)
            /// </summary>
            /// <param name="volumeno">Nummer des gewünschten Volumes (wenn nicht vorhanden, wird nur die Volumeanzahl geliefert)</param>
            /// <returns></returns>
            public VolumeData GetVolumeData(int volumeno)
            {
                VolumeData data = new VolumeData {
                    VolumeNo = volumeno
                };

                if (volumeno >= 0)
                {
                    StorageManager sm = GetStorageManager();
                    if (sm != null)
                    {
                        if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.N) // "Nougat", 7.0
                        {
                            data.Volumes = sm.StorageVolumes.Count;
                            if (0 <= volumeno && volumeno < data.Volumes)
                            {
                                StorageVolume sv = sm.StorageVolumes[volumeno];

                                data.IsPrimary   = sv.IsPrimary;
                                data.IsRemovable = sv.IsRemovable;
                                data.IsEmulated  = sv.IsEmulated;
                                data.Path        = Path4StorageVolume(sv);
                                data.State       = GetVolumeState(sv.State);
                                data.Description = sv.GetDescription(global::Android.App.Application.Context);
                                data.Name        = data.IsPrimary ? ROOT_ID_PRIMARY_EMULATED : sv.Uuid;

                                try {
                                    StatFs statfs = new StatFs(data.Path);
                                    data.AvailableBytes = statfs.AvailableBytes;
                                    data.TotalBytes     = statfs.TotalBytes;
                                } catch {
                                    data.TotalBytes = data.AvailableBytes = 0;
                                }
                            }
                        }
                    }
                }
                else // Daten des internal Storage holen

                {
                    data.IsPrimary   = false;
                    data.IsRemovable = false;
                    data.IsEmulated  = false;
                    data.Path        = System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile); // == Xamarin.Essentials.FileSystem.AppDataDirectory;
                    data.Path        = data.Path.Substring(0, data.Path.LastIndexOf(Path.DirectorySeparatorChar));
                    data.State       = VolumeState.MEDIA_MOUNTED;
                    data.Description = "intern";
                    data.Name        = "intern";
                    try {
                        StatFs statfs = new StatFs(global::Android.OS.Environment.RootDirectory.CanonicalPath);
                        data.AvailableBytes = statfs.AvailableBytes;
                        data.TotalBytes     = statfs.TotalBytes;
                    } catch {
                        data.TotalBytes = data.AvailableBytes = 0;
                    }
                }
                return(data);
            }
Example #10
0
        /// <summary>
        /// Get the number of bytes available on the filesystem rooted at the given File.
        /// </summary>
        /// <param name="root">
        /// The root.
        /// </param>
        /// <returns>
        /// The get available bytes.
        /// </returns>
        public static long GetAvailableBytes(string root)
        {
            var stat = new StatFs(root);

            // put a bit of margin (in case creating the file grows the system by a few blocks)
            long availableBlocks = (long)stat.AvailableBlocks - 4;

            return(stat.BlockSize * availableBlocks);
        }
Example #11
0
        public StorageInfo GetStorageInformation(string path = "")
        {
            try {
                StorageInfo storageInfo = new StorageInfo();

                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 (path == "")
                {
                    totalSpaceBytes     = Android.OS.Environment.ExternalStorageDirectory.TotalSpace;
                    freeSpaceBytes      = Android.OS.Environment.ExternalStorageDirectory.FreeSpace;
                    availableSpaceBytes = Android.OS.Environment.ExternalStorageDirectory.UsableSpace;
                }
                else
                {
                    StatFs stat = new StatFs(path);                     //"/storage/sdcard1"

                    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
                    {
#pragma warning disable CS0618 // Type or member is obsolete
                        totalSpaceBytes     = (long)stat.BlockCount * (long)stat.BlockSize;
                        availableSpaceBytes = (long)stat.AvailableBlocks * (long)stat.BlockSize;
                        freeSpaceBytes      = (long)stat.FreeBlocks * (long)stat.BlockSize;
#pragma warning restore CS0618 // Type or member is obsolete
                    }
                }

                storageInfo.TotalSpace     = totalSpaceBytes;
                storageInfo.AvailableSpace = availableSpaceBytes;
                storageInfo.FreeSpace      = freeSpaceBytes;
                return(storageInfo);
            }
            catch (Exception _ex) {
                error(_ex);
                return(new StorageInfo()
                {
                    AvailableSpace = 0,
                    FreeSpace = 0,
                    TotalSpace = 0,
                });
            }
        }
Example #12
0
        public ulong GetAvailableDiskSpace(FolderUri uri)
        {
            try
            {
                Java.Lang.Process proc =
                    Java.Lang.Runtime.GetRuntime().Exec(String.Format("df {0}", uri.AbsolutePath));

                proc.WaitFor();

                var    resi = proc.InputStream;
                var    rdr  = new StreamReader(resi);
                string str  = rdr.ReadToEnd();

                string[] lines = str.Split('\n');
                if (lines.Length < 2)
                {
                    throw new InvalidOperationException("Unable to get size from shell.");
                }

                string[] entries = lines[1]
                                   .Split(' ')
                                   .Where(e => !String.IsNullOrWhiteSpace(e))
                                   .ToArray();

                string entry = entries[3];

                ulong  value = (ulong)Int32.Parse(entry.Substring(0, entry.Length - 1));
                string unit  = entry.Substring(entry.Length - 1, 1);

                switch (unit)
                {
                // Value is in bytes
                case "B":
                    return(value);

                // Value is in Kbytes
                case "K":
                    return(value * 1024);

                // Value is in Mbytes
                case "M":
                    return(value * 1024 * 1024);

                // Value is in Gbytes
                case "G":
                    return(value * 1024 * 1024 * 1024);

                default:
                    throw new InvalidOperationException("Unknown size unit.");
                }
            }
            catch (Exception ex)
            {
                StatFs stats = new StatFs(uri.AbsolutePath);
                return((ulong)(stats.AvailableBlocks * stats.BlockSize));
            }
        }
Example #13
0
 internal long?GetAvaliableRom()
 {
     try
     {
         var statfs = new StatFs(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal));
         return(statfs.AvailableBytes);
     }
     catch { }
     return(null);
 }
Example #14
0
        public static string GetFreeSpace(Context context)
        {
            if (context == null)
            {
                return(string.Empty);
            }

            var stat            = new StatFs(context.ApplicationInfo.DataDir);
            var blockSize       = stat.BlockSizeLong;
            var availableBlocks = stat.AvailableBlocksLong;

            return(Formatter.FormatFileSize(context, availableBlocks * blockSize));
        }
Example #15
0
 private static bool IsValidPath(string path)
 {
     try
     {
         var stat   = new StatFs(path);
         var blocks = stat.BlockCountLong;
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #16
0
 public static long getInternalCacheMemoryInBytes(Activity act)
 {
     if (act != null)
     {
         string path = getInternalStorageCacheDir(act);
         StatFs stat = new StatFs(path);
         return(stat.getAvailableBytes());
     }
     else
     {
         Log.e(TAG, "activity is null getInternalCacheMemoryInBytes method");
     }
     return(0);
 }
Example #17
0
        StorageInfo IDeviceInformation.GetStorage()
        {
            StorageInfo storageInfo = new StorageInfo();

            StatFs stat = new StatFs(Environment.RootDirectory.AbsolutePath);

            SetStats(storageInfo.LocalStorage, stat);

            stat = new StatFs(Environment.ExternalStorageDirectory.AbsolutePath);

            SetStats(storageInfo.SDStorage, stat);

            return(storageInfo);
        }
Example #18
0
 private static int CalculatePicturesRemaining()
 {
     try
     {
         var storageDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).ToString();
         var stat             = new StatFs(storageDirectory);
         var remaining        = stat.AvailableBlocksLong
                                * (float)stat.BlockSizeLong / 400000F;
         return((int)remaining);
     }
     catch (Exception)
     {
         return(CannotStatError);
     }
 }
Example #19
0
        private long GetAvailableDiskSpace()
        {
            try {
                var externalStat  = new StatFs(Android.OS.Environment.ExternalStorageDirectory.Path);
                var externalAvail = (long)externalStat.BlockSize * (long)externalStat.BlockCount;

                var internalStat  = new StatFs(Android.OS.Environment.DataDirectory.Path);
                var internalAvail = (long)internalStat.BlockSize * (long)internalStat.BlockCount;

                return(Math.Min(externalAvail, internalAvail));
            } catch (Java.Lang.Throwable ex) {
                Log.WriteLine("Failed to determine available disk space: {0}", ex);
                return(0);
            }
        }
Example #20
0
        private void SetStats(StorageBase storage, StatFs stat)
        {
            long totalSpaceBytes     = 0;
            long freeSpaceBytes      = 0;
            long availableSpaceBytes = 0;

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr2)
            {
                totalSpaceBytes     = stat.BlockCountLong * stat.BlockSizeLong;
                availableSpaceBytes = stat.AvailableBlocksLong * stat.BlockSizeLong;
                freeSpaceBytes      = stat.FreeBlocksLong * stat.BlockSizeLong;
            }
            storage.TotalSpace     = totalSpaceBytes;
            storage.AvailableSpace = availableSpaceBytes;
            storage.FreeSpace      = freeSpaceBytes;
        }
 private static int calculatePicturesRemaining()
 {
     try
     {
         string storageDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures).ToString();
         StatFs stat             = new StatFs(storageDirectory);
         float  remaining        = ((float)stat.AvailableBlocks * (float)stat.BlockSize) / 400000F;
         return((int)remaining);
     }
     catch (Exception)
     {
         // if we can't stat the filesystem then we don't know how many
         // pictures are remaining.  it might be zero but just leave it
         // blank since we really don't know.
         return(CANNOT_STAT_ERROR);
     }
 }
Example #22
0
        private static int CalculatePicturesRemaining()
        {
            try {
                var storageDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).ToString();
                var stat             = new StatFs(storageDirectory);
                var remaining        = stat.AvailableBlocksLong * (float)stat.BlockSizeLong / 400000F;

                return((int)remaining);
            }
            catch (Exception)
            {
                // if we can't stat the filesystem then we don't know how many
                // pictures are remaining.  it might be zero but just leave it
                // blank since we really don't know.
                return(CannotStatError);
            }
        }
Example #23
0
        public Task <UInt64> GetFreeSpace()
        {
            var fullExternalStorage = Android.OS.Environment.ExternalStorageDirectory.TotalSpace;
            var freeExternalStorage = Android.OS.Environment.ExternalStorageDirectory.UsableSpace;

            var fullInternalStorage = Android.OS.Environment.RootDirectory.TotalSpace;
            var freeInternalStorage = Android.OS.Environment.RootDirectory.UsableSpace;



            //Using StatFS
            var  path            = new StatFs(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData));
            long blockSize       = path.BlockSizeLong;
            long avaliableBlocks = path.AvailableBlocksLong;
            var  produto         = (blockSize * avaliableBlocks).ToString();

            return(Task.FromResult(UInt64.Parse(produto)));
        }
Example #24
0
        public static ulong FreeMemory(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return(0);
            }
            using (StatFs statFs = new StatFs(path))
            {
                if (Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.JellyBeanMr2) //Build.VERSION_CODES.JellyBeanMr2)
                //noinspection deprecation
#pragma warning disable CS0618                                                        // Type or member is obsolete
                {
                    return((ulong)(statFs.AvailableBlocks * statFs.BlockSize));
                }
#pragma warning restore CS0618 // Type or member is obsolete
                return((ulong)(statFs.AvailableBlocksLong * statFs.BlockSizeLong));
            }
        }
Example #25
0
        internal static MemorySize GetMemorySize(bool useRadix1024)
        {
            MemorySize size = new MemorySize(useRadix1024);

            try
            {
                using (var path = Android.OS.Environment.DataDirectory)
                {
                    using (var stat = new StatFs(path.Path))
                    {
                        size.FreeBytes  = stat.AvailableBytes;
                        size.TotalBytes = stat.TotalBytes;
                    }
                }
            }
            catch
            {
            }
            return(size);
        }
Example #26
0
        public static long CalculateDiskCacheSize(File cacheDir)
        {
            long size = MinDiskCacheSize;

            try
            {
                var statFs = new StatFs(cacheDir.AbsolutePath);

                long available = 0;
                if (Build.VERSION.SdkInt < BuildVersionCodes.JellyBeanMr2)
                {
                    available = statFs.BlockCount * statFs.BlockSize;
                }
                else
                {
                    available = statFs.BlockCountLong * statFs.BlockSizeLong;
                }

                size = available / 50;
            }
            catch (IllegalArgumentException) { }

            return(Math.Max(Math.Min(size, MaxDiskCacheSize), MinDiskCacheSize));
        }
Example #27
0
        void PublishInfo(string msg = "")
        {
            if (!string.IsNullOrEmpty(msg))
            {
                debugTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                debugMsg  = msg;
            }
            Dictionary <string, object> dict = new Dictionary <string, object>();
            // 屏幕亮度
            int brightness = Settings.System.GetInt(this.ContentResolver, Settings.System.ScreenBrightness);
            // 音乐音量
            int musicVolume    = audioManager.GetStreamVolume(Stream.Music);
            int musicVolumeMax = audioManager.GetStreamMaxVolume(Android.Media.Stream.Music);
            // 闹钟音量
            int alarmVolume    = audioManager.GetStreamVolume(Stream.Alarm);
            int alarmVolumeMax = audioManager.GetStreamMaxVolume(Android.Media.Stream.Alarm);
            // 系统音量
            int systemVolume    = audioManager.GetStreamVolume(Stream.System);
            int systemVolumeMax = audioManager.GetStreamMaxVolume(Android.Media.Stream.System);
            // WiFi管理
            WifiManager wifiManager = this.GetSystemService(Context.WifiService) as WifiManager;
            WifiInfo    wifiInfo    = wifiManager.ConnectionInfo;

            // 磁盘容量
            Java.IO.File datapath = Android.OS.Environment.DataDirectory;
            StatFs       dataFs   = new StatFs(datapath.Path);
            // 电量
            string battery = (Xamarin.Essentials.Battery.ChargeLevel * 100).ToString();

            // 充电状态
            string[] batteryState = new string[] { "Unknown", "Charging", "Discharging", "Full", "NotCharging", "NotPresent" };

            dict.Add("设置主题", $"{topic}set");
            dict.Add("语音识别", $"{topic}stt");
            dict.Add("调试时间", debugTime);
            dict.Add("调试消息", debugMsg);

            dict.Add("brightness", brightness);
            dict.Add("充电状态", batteryState[(int)Xamarin.Essentials.Battery.State]);
            dict.Add("音乐音量", musicVolume);
            dict.Add("闹钟音量", alarmVolume);
            dict.Add("系统音量", systemVolume);
            dict.Add("音乐最大音量", musicVolumeMax);
            dict.Add("闹钟最大音量", alarmVolumeMax);
            dict.Add("系统最大音量", systemVolumeMax);

            dict.Add("存储总量", getUnit(dataFs.TotalBytes));
            dict.Add("存储剩余", getUnit(dataFs.AvailableBytes));
            dict.Add("存储使用", getUnit(dataFs.TotalBytes - dataFs.AvailableBytes));

            dict.Add("设备名称", Xamarin.Essentials.DeviceInfo.Name);
            dict.Add("设备型号", Xamarin.Essentials.DeviceInfo.Model);
            dict.Add("设备版本", Xamarin.Essentials.DeviceInfo.VersionString);
            dict.Add("应用版本", Xamarin.Essentials.AppInfo.VersionString);

            dict.Add("本机IP", getIP());
            dict.Add("WiFi名称", wifiInfo.SSID.Trim('"'));
            dict.Add("WiFi信号", wifiInfo.Rssi);
            dict.Add("Mac地址", wifiInfo.MacAddress);

            string state = floatButton != null && floatButton.Visibility == ViewStates.Invisible ? "ON" : "OFF";

            mqttClient.PublishAsync($"{topic}state", state);
            mqttClient.PublishAsync($"{topic}attributes", JsonConvert.SerializeObject(dict));

            // 发送电量信息
            mqttClient.PublishAsync($"{topic}batterySensor/state", battery);
        }
Example #28
0
 private static int calculatePicturesRemaining()
 {
     try
     {
         string storageDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures).ToString();
         StatFs stat = new StatFs(storageDirectory);
         float remaining = ((float)stat.AvailableBlocks
                            * (float)stat.BlockSize) / 400000F;
         return (int)remaining;
     }
     catch (Exception)
     {
         // if we can't stat the filesystem then we don't know how many
         // pictures are remaining.  it might be zero but just leave it
         // blank since we really don't know.
         return CANNOT_STAT_ERROR;
     }
 }
Example #29
0
 public static long getBlockSize(this StatFs statFs)
 {
     return(statFs.BlockSizeLong);
 }
Example #30
0
 public static long getBlockCount(this StatFs statFs)
 {
     return(statFs.BlockCountLong);
 }
        private long GetAvailableDiskSpace()
        {
            try {
                var externalStat = new StatFs (Android.OS.Environment.ExternalStorageDirectory.Path);
                var externalAvail = (long)externalStat.BlockSize * (long)externalStat.BlockCount;

                var internalStat = new StatFs (Android.OS.Environment.DataDirectory.Path);
                var internalAvail = (long)internalStat.BlockSize * (long)internalStat.BlockCount;

                return Math.Min (externalAvail, internalAvail);
            } catch (Java.Lang.Throwable ex) {
                Log.WriteLine ("Failed to determine available disk space: {0}", ex);
                return 0;
            }
        }
Example #32
0
 public static long getAvailableBlocks(this StatFs statFs)
 {
     return(statFs.AvailableBlocksLong);
 }
        /// <summary>
        /// Get the number of bytes available on the filesystem rooted at the given File.
        /// </summary>
        /// <param name="root">
        /// The root.
        /// </param>
        /// <returns>
        /// The get available bytes.
        /// </returns>
        public static long GetAvailableBytes(string root)
        {
            var stat = new StatFs(root);

            // put a bit of margin (in case creating the file grows the system by a few blocks)
            long availableBlocks = (long)stat.AvailableBlocks - 4;
            return stat.BlockSize * availableBlocks;
        }
 public long GetFreeSpace()
 {
     StatFs stat = new StatFs(global::Android.OS.Environment.ExternalStorageDirectory.ToString());
     long bytesAvailable = (long)stat.BlockSize * (long)stat.AvailableBlocks;
     return bytesAvailable;
 }