System.IO.Path.GetDirectoryName Method

Returns the directory information for the specified path string.

Syntax

public static string GetDirectoryName (string path)

Parameters

path
The path of a file or directory.

Returns

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.

Exceptions

TypeReason
ArgumentException path contains one or more implementation-specific invalid characters.

Remarks

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.

Example

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

Requirements

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0