×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

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)

  1. 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 »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.