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 a class DriveInfo provides members that helps you find the drive type, free space and many other information of 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 for getting 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.

 Drive.RootDirectory: We can use the RootDirectory property to determine the root directory.

 Drive.AvailableFreeSpace: It indicates the amount of free space available on a drive.

 DriveInfo: This class is used to display information about all the drives on the current system.

Steps for Get the Total Free Space on a Drive are:

Step1. Open the Visual Studio 2010, click on the new project.

Step2. Select the C# category as shown in the below figure.

2.jpg

Step3. Do the coding as shown below.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

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();

        }

    }

}


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

1.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all