Get The Total Free Space Available On A Drive

Introduction

Here I am showing how we can get the total free space on a Drive. In this, we use the DriveInfo.AvailableFreeSpace property. In this class, DriveInfo provides members that help you find the drive type, free space, and many other information about a drive. We also can retrieve a list of logical drives available by using the StaticDirectory.GetLogicalDrives method. We can also create a DriveInfo instance to get more details on each drive. We can get the details by passing either the root or the letter corresponding to the logical drive. In this, we use IOException so that we can access the unavailable network drive.

  1. Drive.RootDirectory: We can use the RootDirectory property to determine the root directory.
  2. Drive.AvailableFreeSpace: It indicates the amount of free space available on a drive.
  3. DriveInfo: This class is used to display information about all the drives on the current system.

Steps for Getting the Total Free Space on a Drive are.

Step 1. Open the Visual Studio 2010, and click on the new project.

Step 2. Select the C# category as shown in the below figure.

2.jpg

Step 3. Do the coding as shown below.

using System;
using System.Collections.Generic;
using System.IO;
namespace Drive
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                DriveInfo drive = new DriveInfo(args[0]);
                Console.Write("Free space in {0}-drive (in Kilobytes):", args[0]);
                Console.WriteLine(drive.AvailableFreeSpace);
                Console.ReadLine();
                return;
            }
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                try
                {
                    Console.WriteLine("{0}-{1}KB", drive.RootDirectory, drive.AvailableFreeSpace);
                }
                catch (IOException)
                {
                    Console.WriteLine(drive);
                }
            }
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
        }
    }
}

Step 4. After this, press F5; the output for the following code will be shown like this.

output


Similar Articles