C# Program to Get Computer Drive Names of Given Directory
Last Updated :
26 Jan, 2022
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#
using System;
using System.IO;
class GFG{
static void Main()
{
string [] drives_data;
drives_data = Directory.GetLogicalDrives();
Console.WriteLine( "Computer Drives in my system:" );
for ( int i = 0; i < drives_data.Length; i++)
{
Console.WriteLine( drives_data[i]);
}
}
}
|
Output:
Computer Drives in my system:
C:/
D:/
E:/
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...