Calculate drive total/free/available space

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            long? systemTotalSpace = GetDriveTotalSpace(Path.GetPathRoot(Environment.SystemDirectory));
            long? systemAvailableSpace = GetDriveFreeSpace(Path.GetPathRoot(Environment.SystemDirectory));
            long? remoteAvailableSpace = GetDriveOccupiedSpace(Path.GetPathRoot(Environment.SystemDirectory));

            if(systemTotalSpace.HasValue)
                Console.WriteLine("C: total space " + ConvertBytesToGString(systemTotalSpace.Value));

            if (systemAvailableSpace.HasValue)
                Console.WriteLine("C: free space " + ConvertBytesToGString(systemAvailableSpace.Value));

            if (remoteAvailableSpace.HasValue)
                Console.WriteLine("C: occupied space " + ConvertBytesToGString(remoteAvailableSpace.Value));

            Console.ReadKey();
        }

        static string ConvertBytesToGString(long size)
        {
            string[] Suffix = { "b", "K", "M", "G", "T" };
            const long Unit = 1024;

            int sIndex = 0;
            decimal dSize = new decimal(size);

            while (dSize > Unit)
            {
                dSize = dSize / Unit;

                sIndex++;
            }

            return string.Format("{0} {1} ", Math.Round(dSize, 2), Suffix[sIndex]);
        }

        static long? GetDriveOccupiedSpace(string driveName)
        {
            DriveInfo[] allDrives = DriveInfo.GetDrives();

            foreach (DriveInfo d in allDrives)
            {
                if (d.Name.Equals(driveName, StringComparison.OrdinalIgnoreCase))
                {
                    return d.TotalSize - d.TotalFreeSpace;
                }
            }

            return null;
        }
        static long? GetDriveTotalSpace(string driveName)
        {
            DriveInfo[] allDrives = DriveInfo.GetDrives();

            foreach (DriveInfo d in allDrives)
            {
                if (d.Name.Equals(driveName, StringComparison.OrdinalIgnoreCase))
                {
                    return d.TotalSize;
                }
            }

            return null;
        }

        static long? GetDriveFreeSpace(string driveName)
        {
            DriveInfo[] allDrives = DriveInfo.GetDrives();

            foreach (DriveInfo d in allDrives)
            {
                if (d.Name.Equals(driveName, StringComparison.OrdinalIgnoreCase))
                {
                    return d.AvailableFreeSpace; //Available free space for current user
                }
            }

            return null;
        }
    }
}

上一篇:输入两手牌,两手牌之间用“-”连接,每手牌的每张牌以空格分隔,“-”两边没有空格,如:4 4 4 4-joker JOKER 请比较两手牌大小,输出较大的牌,如果不存在比较关系则输出ERROR


下一篇:图片过大,在div中不压缩的居中方法