Returns the directory name component of the specified path string.
- path
- A string containing the path of a file or directory.
A string containing directory information for path, or null if path denotes a root directory, is the empty string, or is null. Returns string.Empty if path does not contain directory information.
Type Reason ArgumentException path contains one or more implementation-specific invalid characters.
The string returned by this method consists of all characters between the first and last Path.DirectorySeparatorChar or Path.AltDirectorySeparatorChar character in path. The first separator character is included, but the last separator character is not included in the returned string.
The following example demonstrates using the Path.GetDirectoryName(string) method on a Windows system.
C# Example
using System; using System.IO; class GetDirectoryTest { public static void Main() { string [] paths = { @"\ecmatest\examples\pathtests.txt", @"\ecmatest\examples\", "pathtests.xyzzy", @"\", @"C:\", @"\\myserver\myshare\foo\bar\baz.txt" }; foreach (string pathString in paths) { string s = Path.GetDirectoryName(pathString); Console.WriteLine("Path: {0} directory is {1}",pathString, s== null? "null": s); } } }The output is
Path: \ecmatest\examples\pathtests.txt directory is \ecmatest\examples
Path: \ecmatest\examples\ directory is \ecmatest\examples
Path: pathtests.xyzzy directory is
Path: \ directory is null
Path: C:\ directory is null
Path: \\myserver\myshare\foo\bar\baz.txt directory is \\myserver\myshare\foo\bar
Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0