DirectoryInfo(String) Constructor

Definition

Initializes a new instance of the DirectoryInfo class on the specified path.

C#
public DirectoryInfo(string path);

Parameters

path
String

A string specifying the path on which to create the DirectoryInfo.

Exceptions

path is null.

The caller does not have the required permission.

.NET Framework and .NET Core versions older than 2.1: path contains invalid characters such as ", <, >, or |.

The specified path, file name, or both exceed the system-defined maximum length.

Examples

The following example uses this constructor to create the specified directory and subdirectory, and demonstrates that a directory that contains subdirectories cannot be deleted.

C#
using System;
using System.IO;

class Test
{
    public static void Main()
    {
        // Specify the directories you want to manipulate.
        DirectoryInfo di1 = new DirectoryInfo(@"c:\MyDir");
        DirectoryInfo di2 = new DirectoryInfo(@"c:\MyDir\temp");

        try
        {
            // Create the directories.
            di1.Create();
            di2.Create();

            // This operation will not be allowed because there are subdirectories.
            Console.WriteLine("I am about to attempt to delete {0}.", di1.Name);
            di1.Delete();
            Console.WriteLine("The Delete operation was successful, which was unexpected.");
        }
        catch (Exception)
        {
            Console.WriteLine("The Delete operation failed as expected.");
        }
        finally {}
    }
}

Remarks

This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations.

The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

Caution

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

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

Applies to

Product Versions
.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