Open In App

C# Program to Get Computer Drive Names of Given Directory

Last Updated : 26 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:/

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads