Open In App

C# Program to Get Root Directory 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. GetDirectoryRoot() is a method of Directory class. This method is used to find the information of the volume or root or both for the given path. Or we can say that this method is used to find the root directory of the given directory.

Syntax:

public static string GetDirectoryRoot (string path);

Here, the path is the location of the directory or file.

Return: This method will return a string that will contain the information of the root or volume of the given path.

Exceptions: This method will throw the following exceptions:

  • UnauthorizedAccessException: This exception will occur when the caller does not have the specified permission.
  • ArgumentException: This exception will occur when the path is a zero-length string, or can contain only white space, or can contain one or more invalid characters.
  • ArgumentNullException: This exception will occur when the path is null.
  • PathTooLongException: This exception will occur when the specified path, file name, or both exceed the system-defined maximum length.

Example:

C#




// C# program find the root directory of the given directory
using System;
using System.IO;
  
class GFG{
  
static void Main()
{
      
    // Get the root directory for the path specified
    // Using GetDirectoryRoot() method
    Console.WriteLine(Directory.GetDirectoryRoot("D:/Sravan/Vignan"));
      
    // Get the root directory for the path specified
    // Using GetDirectoryRoot() method
    Console.WriteLine(Directory.GetDirectoryRoot("C:/Sravan/Vignan"));
      
    // Get the root directory for the path specified
    // Using GetDirectoryRoot() method
    Console.WriteLine(Directory.GetDirectoryRoot("F:/Sravan"));
}
}


Output:

D
C
F

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads