Exemplo n.º 1
0
        public static DiskSpaceResult GetFreeDiskSpace(string pathToCheck, DriveInfo[] driveInfo)
        {
            if (string.IsNullOrEmpty(pathToCheck))
            {
                return(null);
            }

            if (PlatformDetails.RunningOnPosix)
            {
                var statvfs = default(Statvfs);
                if (Syscall.statvfs(pathToCheck, ref statvfs) != 0)
                {
                    return(null);
                }

                return(new DiskSpaceResult
                {
                    DriveName = Syscall.GetRootMountString(pathToCheck),
                    TotalFreeSpace = new Size((long)(statvfs.f_bsize * statvfs.f_bfree), SizeUnit.Bytes),
                    TotalSize = new Size((long)(statvfs.f_bsize * statvfs.f_blocks), SizeUnit.Bytes)
                });
            }

            if (Path.IsPathRooted(pathToCheck) && pathToCheck.StartsWith("\\\\") == false)
            {
                var root = Path.GetPathRoot(pathToCheck);

                foreach (var drive in driveInfo)
                {
                    if (root.Contains(drive.Name) == false)
                    {
                        continue;
                    }

                    return(new DiskSpaceResult
                    {
                        DriveName = root,
                        TotalFreeSpace = new Size(drive.TotalFreeSpace, SizeUnit.Bytes),
                        TotalSize = new Size(drive.TotalSize, SizeUnit.Bytes)
                    });
                }

                return(null);
            }

            if (pathToCheck.StartsWith("\\\\"))
            {
                var uncRoot = Path.GetPathRoot(pathToCheck);

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

                if (success == false)
                {
                    return(null);
                }

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

            return(null);
        }