Open In App

C# Program to Get Computer Drive Names of Given Directory

Directory class provides different types of methods for creating, moving, deleting, renaming, and modifying directories and subdirectories. GetLogicalDrives() is the method of the Directory class. This method is used to find the name of the logical drive names present in the computer. Or we can say that this method returns the drive names of the given directory. The returned string is represented like this “<drive name>:\”.

Syntax:



string[] Directory.GetLogicalDrives();

Return: It will return the directory names with string type.



Exception: This method will throw the following exception:

Approach:

1. Create a variable to initiate the drive data named “drives_data”.

2. Now find the name of the drives present in the computer system using the GetLogicalDrives() method.

3. Now use the length function to get the length of drives for displaying inside for loop

for(int i = 0; i < drives_data.Length; i++)
{
    // Display drive names
    Console.WriteLine(drives_data[i]);
}

Example:




// C# program to find the computer drive names
// of given directory
using System;
using System.IO;
  
class GFG{
      
static void Main()
{
    string[] drives_data;
      
    // Getting the drives names
    // Using GetLogicalDrives() method
    drives_data = Directory.GetLogicalDrives();
      
    Console.WriteLine("Computer Drives in my system:");
    for(int i = 0; i < drives_data.Length; i++)
    {
          
        // Display drive names
        Console.WriteLine( drives_data[i]);
    }
}
}

Output:

Computer Drives in my system:
C:/
D:/
E:/
Article Tags :