Directory information for path, or null if path denotes a root directory 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.
In most cases, the string returned by this method consists of all characters in the path up to but not including the last Path.DirectorySeparatorChar or Path.AltDirectorySeparatorChar. If the path consists of a root directory, such as "c:\", null is returned. Note that this method does not support paths using "file:". Because the returned path does not include the Path.DirectorySeparatorChar or Path.AltDirectorySeparatorChar, passing the returned path back into the Path.GetDirectoryName(string) method will result in the truncation of one folder level per subsequent call on the result string. For example, passing the path "C:\Directory\SubDirectory\test.txt" into the Path.GetDirectoryName(string) method will return "C:\Directory\SubDirectory". Passing that string, "C:\Directory\SubDirectory", into Path.GetDirectoryName(string) will result in "C:\Directory".
For a list of common I/O tasks, see Common I/O Tasks.
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