C# Program to get the name of root directory

Use the RootDirectory property to get the name of the root directory of a drive in C#. This property belongs to the DriveInfo class and returns a DirectoryInfo object representing the root directory.

Syntax

Following is the syntax for getting the root directory −

DriveInfo driveInfo = new DriveInfo("driveLetter");
DirectoryInfo rootDir = driveInfo.RootDirectory;

Using DriveInfo.RootDirectory Property

First, create a DriveInfo object to specify the drive for which you want the root directory −

DriveInfo dInfo = new DriveInfo("C");

Then, the RootDirectory property gives you the root directory −

dInfo.RootDirectory

Example

Here is a complete program demonstrating how to get the root directory −

using System;
using System.IO;

public class Demo {
   public static void Main() {
      DriveInfo dInfo = new DriveInfo("C");
      Console.WriteLine("Root Directory: " + dInfo.RootDirectory);
   }
}

The output of the above code is −

Root Directory: C:\

Getting Root Directory for Multiple Drives

Example

You can also iterate through all available drives and get their root directories −

using System;
using System.IO;

public class Demo {
   public static void Main() {
      DriveInfo[] drives = DriveInfo.GetDrives();
      
      Console.WriteLine("Available drives and their root directories:");
      foreach (DriveInfo drive in drives) {
         if (drive.IsReady) {
            Console.WriteLine("Drive: " + drive.Name + " - Root: " + drive.RootDirectory);
         }
      }
   }
}

The output of the above code is −

Available drives and their root directories:
Drive: C:\ - Root: C:\
Drive: D:\ - Root: D:\

Getting Root Directory Name Only

Example

If you need just the name without additional path information, use the Name property −

using System;
using System.IO;

public class Demo {
   public static void Main() {
      DriveInfo dInfo = new DriveInfo("C");
      Console.WriteLine("Root Directory Name: " + dInfo.RootDirectory.Name);
      Console.WriteLine("Root Directory Full Name: " + dInfo.RootDirectory.FullName);
   }
}

The output of the above code is −

Root Directory Name: C:\
Root Directory Full Name: C:\

Conclusion

The DriveInfo.RootDirectory property provides an easy way to get the root directory of any drive. Use DriveInfo.GetDrives() to enumerate all available drives and their root directories programmatically.

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

704 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements