C# Path.GetDirectoryName (Remove File From Path)Use the Path.GetDirectoryName method from the System.IO namespace. Remove the file name from the path.
finds a directory name from a path. We look at this .NET Framework method. We then look inside it and develop an optimized version. It is possible to remove certain features from its implementation.Directory
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. 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.
C# program that uses Path.GetDirectoryName
static void Main()
// Example path.
string path = @"C:\Users\Sam\Documents\Test.txt";
// Get the directory name.
Path tries to detect all invalid paths and fix them if necessary. However, these automatic fixes can cause more harm than good. Internally, it runs large and complicated internal routines.
Note: Many developers advise using the Path static class methods such as GetDirectory.
Next, we look at an alternate way you can get the directory part of the string. You can simplify GetDirectory by eliminating the first steps in the algorithm noted above, and simply using LastIndexOf and Substring.LastIndexOfSubstring
Info: This method is more predictable and traps its own exceptions, making for potentially simpler calling code. It is also ten times faster.
Note: This makes sense because it has two lines of code compared to hundreds or more in Path.GetDirectory.
C# program that uses alternative path method
static void Main()
string p = @"C:\Users\Sam\Documents\Test.txt";
static string GetDirectoryName(string f)
return f.Substring(0, f.LastIndexOf('\\'));
You may be wondering how must faster the custom method shown is than the static Path method. I was interested in speed here because the code runs almost 100,000 times a day. The computer running it is also slow.Benchmark
Input string: @"C:\Users\Sam\Documents\Test.txt
Path.GetDirectoryName time: 6780 ms
String method: 547 ms
We looked into Path.GetDirectoryName with IL Disassembler. We observed what it does internally. Then we took the very core of the code and extracted it into an alternative method. We tested the results.IL Disassembler
Tip: To simplify your program's control flow, you can copy and paste the internal implementations of the .NET Framework methods.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.