Skip to main content

How to Point to a Folder with DirectoryInfo in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

new DirectoryInfo("backups") makes an object that points to a folder named backups. It doesn't create the folder or even check that it's there: it holds the path, and its properties and methods go to the disk when you use them.

Some .NET methods ask for a folder as a DirectoryInfo and not as a string. The .NET API reference on the class: Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.

You make one with new and a path. The constructor's reference says what that does, and what it doesn't: 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. So the folder doesn't have to exist yet.

Syntax​

Syntax
DirectoryInfo <folder> = new("<path>");

<folder>.Name
<folder>.FullName
<folder>.Exists
<folder>.Create();
PartWhat it is
DirectoryInfo <folder>A variable that holds the object
new("<path>")Makes the object. A relative path, such as backups, becomes a full path inside the current folder
<folder>.NameOnly the folder's own name, the last part of the path
<folder>.FullNameThe whole path. The reference: Gets the full path of the directory or file.
<folder>.ExistsTrue when the folder is there. The reference: Gets a value indicating whether the directory exists.
<folder>.Create()Creates the folder. The reference: If the directory already exists, this method does nothing.

The Example​

A console app called DirectoryInfoFolder points a DirectoryInfo at a folder named backups that isn't there yet. It prints the folder's name, its full path and whether it exists, creates it, and then passes the same object to a method that counts the files in it.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n DirectoryInfoFolder
cd DirectoryInfoFolder
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/DirectoryInfoFolder/DirectoryInfoFolder.csproj:
Determining projects to restore...
Restored /Users/you/source/DirectoryInfoFolder/DirectoryInfoFolder.csproj (in 43 ms).
Restore succeeded.

dotnet new console -n DirectoryInfoFolder creates a folder named DirectoryInfoFolder with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or DirectoryInfoFolder.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First, the object and what it knows:

Program.cs (point to the folder)
// Points to a folder named backups in the current folder. Nothing is created yet.
DirectoryInfo backups = new("backups");
Console.WriteLine($"Name: {backups.Name}");
Console.WriteLine($"Full path: {backups.FullName}");
Console.WriteLine($"Exists: {backups.Exists}");

new("backups") is short for new DirectoryInfo("backups"): the type is already on the left of the =, so C# fills it in. The object holds the path, and nothing on the disk changes. The three lines after it print Name, FullName and Exists.

Then the folder itself:

Program.cs (create the folder)
// Create makes the folder, and does nothing if it's already there.
backups.Create();
Console.WriteLine($"Exists after Create: {backups.Exists}");

Create() makes the folder on the disk, and then Exists is read again.

Then a method that asks for a DirectoryInfo:

Program.cs (pass the object on)
// The same object can be passed to any method that asks for a DirectoryInfo.
CountFiles(backups);

static void CountFiles(DirectoryInfo folder) =>
Console.WriteLine($"{folder.Name} has {folder.GetFiles().Length} files.");

CountFiles takes a DirectoryInfo and gets the same backups object. GetFiles() returns the files in the folder as an array, and Length counts them.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Name: backups
Full path: /Users/you/source/DirectoryInfoFolder/backups
Exists: False
Exists after Create: True
backups has 0 files.

macOS-style terminal window titled Terminal — DirectoryInfoFolder showing dotnet run printing Name: backups, Full path: /Users/you/source/DirectoryInfoFolder/backups, Exists: False, Exists after Create: True and backups has 0 files.

Exists: False shows that new created nothing. The full path ends in the project folder, because dotnet run ran there and backups is a relative path. After Create(), the same object read True. The reference explains why it didn't keep the old answer: If the directory did not exist before calling this method, then any cached attribute information about the directory will be flushed if the creation is successful. The new folder held 0 files.

The Complete File​

macOS-style code window titled Program.cs — DirectoryInfoFolder showing a DirectoryInfo made with new for the backups folder, lines that print its Name, FullName and Exists, a call to Create followed by Exists again, and a CountFiles method that takes a DirectoryInfo and prints how many files GetFiles finds

Program.cs
// Points to a folder named backups in the current folder. Nothing is created yet.
DirectoryInfo backups = new("backups");
Console.WriteLine($"Name: {backups.Name}");
Console.WriteLine($"Full path: {backups.FullName}");
Console.WriteLine($"Exists: {backups.Exists}");

// Create makes the folder, and does nothing if it's already there.
backups.Create();
Console.WriteLine($"Exists after Create: {backups.Exists}");

// The same object can be passed to any method that asks for a DirectoryInfo.
CountFiles(backups);

static void CountFiles(DirectoryInfo folder) =>
Console.WriteLine($"{folder.Name} has {folder.GetFiles().Length} files.");

Common Mistakes​

MistakeWhat happensDo this instead
Expecting new DirectoryInfo("backups") to create the folderThe run printed Exists: False right after new: the constructor only holds the pathCall Create() when the folder must exist
Reading Exists again after the folder was created some other way, such as with Directory.CreateDirectoryA check printed Exists: False, then Exists after Directory.CreateDirectory: False, although the folder was there: the object kept the answer it read first. The Refresh reference: Call Refresh before attempting to get the attribute information, or the information will be outdated.Call Refresh() before reading it. After that, the same check printed Exists after Refresh: True
Listing the files of a folder that isn't there, as in new DirectoryInfo("reports") and then GetFiles()The app stopped with Unhandled exception. System.IO.DirectoryNotFoundException: Could not find a part of the path '/Users/you/source/DirectoryInfoFolder/reports'.Call Create() first, or check Exists before listing

FAQ​

What happens when the app runs a second time?​

The backups folder is already there from the first run, so Exists is True from the start, and Create() does nothing. A second dotnet run printed:

Output
Name: backups
Full path: /Users/you/source/DirectoryInfoFolder/backups
Exists: True
Exists after Create: True
backups has 0 files.

Should I use DirectoryInfo or the Directory class?​

Both work with folders. Directory has static methods that take the path every time, and a DirectoryInfo keeps one path for many calls. The Directory reference: If you are performing only one directory-related action, it might be more efficient to use a static Directory method rather than a corresponding DirectoryInfo instance method. The DirectoryInfo reference: If you are going to reuse an object several times, consider using the instance method of DirectoryInfo instead of the corresponding static methods of the Directory class, because a security check will not always be necessary. And when a method asks for a DirectoryInfo, as CountFiles does, pass one.

Conclusion​

new DirectoryInfo(path) gives you an object for a folder, whether the folder exists yet or not. Read Name, FullName and Exists from it, and call Create() to make the folder. When something else may have changed the folder, call Refresh() before you read Exists again. Then pass the object to any method that asks for a DirectoryInfo.

Additional Resources​