Path.GetDirectoryName
This C# method finds a directory name from a path. It handles path formats in a reliable way. We look at this method from System.IO
.
We look inside GetDirectoryName
and develop an optimized version. It is possible to remove certain features from its implementation.
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.
GetDirectoryName
method will remove any file name part of the path.using System; using System.IO; class Program { static void Main() { // Example path. string path = @"C:\Users\Sam\Documents\Test.txt"; // Get the directory name. Console.WriteLine(Path.GetDirectoryName(path)); } }C:\Users\Sam\Documents
Path
optimizationIs 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.
Path.GetDirectoryName
method. It has more support for different paths.GetDirectory
by eliminating the first steps in the internal method, and use LastIndexOf
and Substring
.GetDirectoryName()
method is significantly faster in this small benchmark.char
being tested.using System; using System.Diagnostics; using System.IO; class Program { static string GetDirectoryName(string value) { // This char may need to be changed. var last = value.LastIndexOf('/'); if (last == -1) { return string.Empty; } return value.Substring(0, last); } const int _max = 1000000; static void Main() { Console.WriteLine(Path.GetDirectoryName( @"/Users/sam/Documents/Test.txt")); Console.WriteLine(GetDirectoryName( @"/Users/sam/Documents/Test.txt")); 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"); } s1.Stop(); 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"); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }/Users/sam/Documents /Users/sam/Documents 29.52 ns Path.GetDirectoryName 11.74 ns GetDirectoryName
Path
tries to detect all invalid paths and fix them if necessary. However, these automatic fixes can be slow—they involve complicated internal routines.
Path
static
class
methods such as GetDirectory
.We looked into Path.GetDirectoryName
and observed its input and output. This method returns a string
indicating the containing directory.