Example program. First, there are many advantages to the Path static class in the base class library, but it also has drawbacks. It checks extensively for errors.
And How much you want error detection and correction depends on your application.
Info When called, the GetDirectoryName method will remove any file name part of the path.
static void Main()
// Example path.
string path = @"C:\Users\Sam\Documents\Test.txt";
// Get the directory name.
Path optimization. Is the GetDirectoryName() method fully optimized in .NET 7 in 2022? We test whether we should still use a custom string method to check some paths.
Version 2 This version of the code uses the built-in Path.GetDirectoryName method. It has more support for different paths.
Version 1 We simplify GetDirectory by eliminating the first steps in the internal method, and use LastIndexOf and Substring.
Result The custom simplified GetDirectoryName() method is significantly faster in this small benchmark.
Warning For using .NET 7 on Windows, Linux and MacOS, you may need to modify the path separator char being tested.
static string GetDirectoryName(string value)
// This char may need to be changed.
var last = value.LastIndexOf('/');
if (last == -1)
return value.Substring(0, last);
const int _max = 1000000;
static void Main()
var s1 = Stopwatch.StartNew();
// Version 1: use Path function.for (int i = 0; i < _max; i++)
var result = Path.GetDirectoryName( @"/Users/sam/Documents/Test.txt");
var s2 = Stopwatch.StartNew();
// Version 2: use simple custom function.for (int i = 0; i < _max; i++)
var result = GetDirectoryName( @"/Users/sam/Documents/Test.txt");
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
29.52 ns Path.GetDirectoryName
11.74 ns GetDirectoryName
Notes, internals. Path tries to detect all invalid paths and fix them if necessary. However, these automatic fixes can be slow—they involve complicated internal routines.
Note Many developers advise using the Path static class methods such as GetDirectory.
A summary. We looked into Path.GetDirectoryName and observed its input and output. This method returns a string indicating the containing directory.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 12, 2022 (new example).