Skip to content
Related Articles
Open in App
Not now

Related Articles

C# Program to Get Computer Drive Names of Given Directory

Improve Article
Save Article
  • Last Updated : 26 Jan, 2022
Improve Article
Save Article

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:

  • IOException: This exception will occur when the I/O error appears.
  • UnauthorizedAccessException: This exception will occur when the caller does not have the specified permissions.

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#




// 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:/
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!