C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Example. 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.
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.
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.
Performance. You may be wondering how must faster the custom method shown is than the static Path method. I was interested in speed here because he runs this code almost 100,000 times a day. The computer running it is also slow.
Benchmark notes Iterations: 12000000 Input string: @"C:\Users\Sam\Documents\Test.txt Path.GetDirectoryName time: 6780 ms String method: 547 ms
Summary. 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.
Tip: To simplify your program's control flow, you can copy and paste the internal implementations of the .NET Framework methods.