Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to display the name of the directory
In C# programming, you can display the name of a directory using the DirectoryInfo class from the System.IO namespace. This class provides properties and methods to work with directory information, including retrieving just the directory name without the full path.
Syntax
Following is the syntax for creating a DirectoryInfo object and accessing the directory name −
DirectoryInfo dir = new DirectoryInfo(directoryPath); string directoryName = dir.Name;
Parameters
- directoryPath − A string representing the path to the directory
Return Value
The Name property returns a string containing only the name of the directory, without the full path.
Using DirectoryInfo.Name Property
The Name property extracts just the directory name from the full path. For example, if the path is C:\Users\Documents, the Name property will return Documents.
Example
using System.IO;
using System;
public class Program {
public static void Main() {
DirectoryInfo dir = new DirectoryInfo(@"D:\new");
// displaying the name of the directory
Console.WriteLine("Directory name: " + dir.Name);
}
}
The output of the above code is −
Directory name: new
Using Multiple Directory Paths
Example
using System.IO;
using System;
public class Program {
public static void Main() {
// Different directory paths
string[] paths = {
@"C:\Users\Documents",
@"D:\Projects\WebApp",
@"/home/user/downloads"
};
foreach (string path in paths) {
DirectoryInfo dir = new DirectoryInfo(path);
Console.WriteLine("Full path: " + path);
Console.WriteLine("Directory name: " + dir.Name);
Console.WriteLine();
}
}
}
The output of the above code is −
Full path: C:\Users\Documents Directory name: Documents Full path: D:\Projects\WebApp Directory name: WebApp Full path: /home/user/downloads Directory name: downloads
Using Current Directory
You can also get the name of the current working directory using Directory.GetCurrentDirectory() method −
Example
using System.IO;
using System;
public class Program {
public static void Main() {
// Get current directory path
string currentPath = Directory.GetCurrentDirectory();
DirectoryInfo currentDir = new DirectoryInfo(currentPath);
Console.WriteLine("Current directory full path: " + currentPath);
Console.WriteLine("Current directory name: " + currentDir.Name);
}
}
The output of the above code is −
Current directory full path: C:\Program Files\dotnet Current directory name: dotnet
Conclusion
The DirectoryInfo class in C# provides an easy way to extract directory names from full paths using the Name property. This is useful when you need to display or work with just the directory name without the complete path information.
