C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
Note: Many developers advise using the Path static class methods such as GetDirectory.
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
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
Benchmark notes
Iterations: 12000000
Input string: @"C:\Users\Sam\Documents\Test.txt
Path.GetDirectoryName time: 6780 ms
String method: 547 ms
Tip: To simplify your program's control flow, you can copy and paste the internal implementations of the .NET Framework methods.