DirectoryInfo.Parent Property

Definition

Gets the parent directory of a specified subdirectory.

C#
public System.IO.DirectoryInfo Parent { get; }
C#
public System.IO.DirectoryInfo? Parent { get; }

Property Value

The parent directory, or null if the path is null or if the file path denotes a root (such as \, C:\, or \\server\share).

Exceptions

The caller does not have the required permission.

Examples

The following example refers to the parent directory of a specified directory.

C#
using System;
using System.IO;

public class MoveToTest
{
    public static void Main()
    {

        // Make a reference to a directory.
        DirectoryInfo di = new DirectoryInfo("TempDir");

        // Create the directory only if it does not already exist.
        if (!di.Exists)
            di.Create();

        // Create a subdirectory in the directory just created.
        DirectoryInfo dis = di.CreateSubdirectory("SubDir");

        // Get a reference to the parent directory of the subdirectory you just made.
        DirectoryInfo parentDir = dis.Parent;
        Console.WriteLine("The parent directory of '{0}' is '{1}'", dis.Name, parentDir.Name);

        // Delete the parent directory.
        di.Delete(true);
    }
}

Remarks

Viktigt

In .NET Framework, Parent returns a relative path. In .NET Core, Parent returns a fully qualified path.

To ensure consistent behavior across versions and to make your intent explicit, retrieve the value of one of the following properties on the DirectoryInfo instance returned by Parent.

  • Name, which returns the simple name of the directory (such as bin).
  • FullName, which returns the absolute path of the directory.

For a list of common I/O tasks, see Common I/O Tasks.

Applies to

Produkt Versioner
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

See also