Home »
.Net »
C# Programs
C# - How to Get Root Directory of the Given Directory?
Learn, how to get root directory of given directory using C# program?
Submitted by IncludeHelp, on November 13, 2017 [Last updated : March 26, 2023]
Get Root Directory of the Given Directory
To get root directory of the given directory in C#, we use Directory.GetDirectoryRoot() method.
Directory.GetDirectoryRoot()
This is a method of 'Directory' class, it returns the root directory name.
Syntax
string Directory. GetDirectoryRoot(string path);
Parameter(s)
- path - It is a location of directory.
Return Value
This method returns the string that contains root-directory.
C# program to get root directory of the given directory
using System;
using System.IO;
namespace ConsoleApplication1 {
class Program {
static void Main() {
string rootDir = "";
rootDir = Directory.GetDirectoryRoot("D:/Sample/dir2/Green color");
Console.WriteLine("Root Directory is : (" + rootDir + ")");
rootDir = Directory.GetDirectoryRoot("D:/Sample/dir2/Blue color");
Console.WriteLine("Root Directory is : (" + rootDir + ")");
rootDir = Directory.GetDirectoryRoot("C:/Windows/Help/Windows");
Console.WriteLine("Root Directory is : (" + rootDir + ")");
}
}
}
Output
Root Directory is : (D:\)
Root Directory is : (D:\)
Root Directory is : (C:\)
Explanation
In the above program, we need to remember, when we use "Directory" class, System.IO namespace must be included in the program.
C#.Net Directory Class Programs »