C# Program to get the name of the drive

The DriveInfo class in C# provides information about drives on the system. You can use the Name property to get the name of a specific drive by passing the drive letter to the DriveInfo constructor.

Syntax

Following is the syntax for creating a DriveInfo object and getting the drive name −

DriveInfo info = new DriveInfo("driveLetter");
string driveName = info.Name;

Parameters

  • driveLetter − A string representing the drive letter (e.g., "C", "D", "E").

Return Value

The Name property returns a string containing the name of the drive, including the drive letter followed by a colon and backslash (e.g., "C:").

Example

The following example demonstrates how to get the name of a specific drive −

using System;
using System.IO;

public class Demo {
   public static void Main() {
      DriveInfo info = new DriveInfo("C");
      Console.WriteLine("Drive: " + info.Name);
   }
}

The output of the above code is −

Drive: C:\

Getting Names of All Available Drives

You can also retrieve the names of all available drives on the system using the GetDrives() method −

using System;
using System.IO;

public class Demo {
   public static void Main() {
      DriveInfo[] drives = DriveInfo.GetDrives();
      
      Console.WriteLine("Available drives:");
      foreach (DriveInfo drive in drives) {
         Console.WriteLine("Drive Name: " + drive.Name);
      }
   }
}

The output of the above code is −

Available drives:
Drive Name: C:\
Drive Name: D:\
Drive Name: E:\

Getting Drive Information with Error Handling

It's good practice to include error handling when working with drives, as some drives may not be accessible −

using System;
using System.IO;

public class Demo {
   public static void Main() {
      try {
         DriveInfo info = new DriveInfo("C");
         Console.WriteLine("Drive Name: " + info.Name);
         Console.WriteLine("Drive Type: " + info.DriveType);
         Console.WriteLine("Is Ready: " + info.IsReady);
      }
      catch (Exception ex) {
         Console.WriteLine("Error: " + ex.Message);
      }
   }
}

The output of the above code is −

Drive Name: C:\
Drive Type: Fixed
Is Ready: True

Conclusion

The DriveInfo class in C# provides an easy way to get drive information, including the drive name using the Name property. You can work with specific drives by passing the drive letter to the constructor, or retrieve information about all available drives using GetDrives().

Updated on: 2026-03-17T07:04:35+05:30

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements