Skip to content
Related Articles
Open in App
Not now

Related Articles

C# Program to Get Root Directory of Given Directory

Improve Article
Save Article
  • Last Updated : 26 Jan, 2022
Improve Article
Save Article

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
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!