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 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)); } } Output C:\Users\Sam\Documents

The Path static class

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.

Example 2.

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
C# program that uses alternative path method using System; using System.IO; class Program { static void Main() { string p = @"C:\Users\Sam\Documents\Test.txt"; Console.WriteLine(GetDirectoryName(p)); } static string GetDirectoryName(string f) { try { return f.Substring(0, f.LastIndexOf('\\')); } catch { return string.Empty; } } } Output C:\Users\Sam\Documents

What are the advantages

with the custom method shown? It 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.


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
Benchmark notes Iterations: 12000000 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.

Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen,