C# program to read the list of available disk drives

Learn, how to read the list of available disk drives in C#? By Nidhi Last updated : April 03, 2023

C# DriveInfo Class Example

Here, we will read the list of available disk drives using DriveInfo class and print the drives name, drive type, and size of the drive on the console screen.

C# code to read and print the list of available disk drives

The source code to read the list of available disk drives is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to read the list of available disk drives.

using System.IO;
using System;

class Demo
{
    static void ReadDrives()
    {
        DriveInfo[] drvList = DriveInfo.GetDrives();

        foreach (DriveInfo drv in drvList)
        {
            Console.WriteLine("Drive Name: "+ drv.Name      );
            Console.WriteLine("\tDrive Type: "+ drv.DriveType );
            
            if (drv.IsReady == true)
            {
                long size=0;
                size = (drv.TotalSize) / (1024*1024*1024);
                Console.WriteLine("\tSize of drive in GB "+size +"\n");    
            }
        }
    }
    public static void Main()
    {
        ReadDrives();
    }
}

Output

Drive Name: C:\
        Drive Type: Fixed
        Size of drive in GB 50

Drive Name: D:\
        Drive Type: Fixed
        Size of drive in GB 97

Drive Name: E:\
        Drive Type: Fixed
        Size of drive in GB 97

Drive Name: F:\
        Drive Type: CDRom
Drive Name: H:\
        Drive Type: Removable
Press any key to continue . . .

Explanation

In the above program, we created a class Demo that contains two static methods ReadDrives() and Main().

In the ReadDrives() class we read available disk drives and print the disk name, disk type, and size of the disk in GigaBytes on the console screen using DriveInfo class. 

The Main() method is the entry point of the program, here we called the static method ReadDrives().

C# Files Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.