예제 #1
0
        public static DiskSpaceResult GetDiskSpaceInfo(string pathToCheck, DriveInfoBase driveInfoBase = null)
        {
            if (string.IsNullOrEmpty(pathToCheck))
            {
                return(null);
            }

            if (PlatformDetails.RunningOnPosix)
            {
                var statvfs = default(Statvfs);
                var result  = Syscall.statvfs(pathToCheck, ref statvfs);
                if (result != 0)
                {
                    var error = Syscall.ErrorNumberToStatusCode(result) ?? result.ToString();
                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info($"Failed to get file system statistics for path: {pathToCheck}, error: {error}");
                    }

                    return(null);
                }

                return(new DiskSpaceResult
                {
                    DriveName = driveInfoBase?.DriveName,
                    TotalFreeSpace = new Size((long)(statvfs.f_bsize * statvfs.f_bavail), SizeUnit.Bytes),
                    TotalSize = new Size((long)(statvfs.f_bsize * statvfs.f_blocks), SizeUnit.Bytes)
                });
            }

            var success = GetDiskFreeSpaceEx(pathToCheck, out var freeBytesAvailable, out var totalNumberOfBytes, out _);

            if (success == false)
            {
                if (Logger.IsInfoEnabled)
                {
                    var error = Marshal.GetLastWin32Error();
                    Logger.Info($"Failed to get the free disk space, path: {pathToCheck}, error: {error}");
                }
                return(null);
            }

            var driveName = driveInfoBase?.DriveName;

            return(new DiskSpaceResult
            {
                DriveName = driveName,
                VolumeLabel = GetVolumeLabel(driveName),
                TotalFreeSpace = new Size((long)freeBytesAvailable, SizeUnit.Bytes),
                TotalSize = new Size((long)totalNumberOfBytes, SizeUnit.Bytes)
            });
        }