1. Introduction
Imagine you're writing an app where a user uploads their photos. It's better not to dump them all into one folder, but to create separate directories — by date or by username. Or say your app generates reports: it's sensible to put results into a dedicated directory that you create on the fly. And deleting temp folders after work is a responsibility of polite code (and a convenience for the user).
Working with directories is a standard task in many applications: from backups to games that want to organize saves into folders. This topic often comes up at interviews, because it's important to understand not just the "create" or "delete" command, but how it behaves in edge cases.
A directory (or folder) is basically a container for files and other directories in the filesystem. Directories form a tree structure (filesystem tree): every folder has a parent, except the topmost root, and can have child folders — even thousands of them.
2. How to create a folder? The static class Directory
The simplest way to create a folder is to use the static method Directory.CreateDirectory. You don't need to create any objects, just pass the path:
using System.IO;
// Create the "Reports" folder in the current directory
Directory.CreateDirectory("Reports");
If such a folder already exists, the method does nothing and doesn't throw — you can safely call CreateDirectory without worrying whether the folder exists.
Let's try a more complex path, for example creating a nested folder:
Directory.CreateDirectory(@"Data\Photos\2024\June");
This call will create the whole chain of directories if some intermediate folders didn't exist. That's called recursive creation — Directory.CreateDirectory will take care of everything.
Important! In directory paths use either a double backslash (\\) for Windows, or a forward slash (/). Even better — use Path.Combine, which we talked about earlier.
What does CreateDirectory return?
The method returns an object of type DirectoryInfo. That's handy if you want to work with that directory immediately:
DirectoryInfo reportsDir = Directory.CreateDirectory("Reports");
Console.WriteLine($"Created folder: {reportsDir.FullName}");
How to check if a folder exists?
Whenever you want to perform an operation on a directory, it's good to make sure it exists. There's a static method for that:
bool exists = Directory.Exists("Reports");
if (!exists)
{
Console.WriteLine("Folder not found, creating it now!");
Directory.CreateDirectory("Reports");
}
Note: You don't have to pre-check before creating: the method won't break anything if the folder exists. But if you want to show a nice message to the user or branch logic differently, this approach is useful.
3. Creating directories: practical cases
Let's apply these ideas to our tutorial app. Suppose we keep records of users and want to store a separate folder for each:
// Add System.IO at the top of the file if it's not there
using System.IO;
Console.Write("Enter user name: ");
string userName = Console.ReadLine() ?? "Unknown";
// Build the path to the user's folder
string basePath = "UsersData";
string userPath = Path.Combine(basePath, userName);
// Create the folder for the user (and the parent if needed)
Directory.CreateDirectory(userPath);
Console.WriteLine($"User folder \"{userName}\" is ready: {Path.GetFullPath(userPath)}");
The example above will create the file structure (if it didn't exist):
UsersData/
└── UserName/
Tip: Always use Path.Combine when joining path parts — this way your code will work on Windows, Linux, and Mac.
4. How to delete a folder? The Directory.Delete method
Deleting a folder is almost as simple as creating one. But there are nuances.
Directory.Delete("Reports");
If the folder exists and is empty — it will be deleted fine. But if it contains something, an exception will be thrown:
System.IO.IOException: "The directory is not empty."
What if you need to delete a folder with contents?
There's an overload for that — with the recursive: true parameter:
Directory.Delete("Reports", recursive: true);
WARNING: Recursive deletion irreversibly destroys everything inside the folder. If you point to the wrong directory, you can lose important data. Always double-check the path!
Example
Add an option to delete a user's folder (for example, when a user deletes their account):
// Ask whether to delete
Console.Write("Delete user's folder? (y/n): ");
string input = Console.ReadLine() ?? "";
if (input.ToLower() == "y")
{
if (Directory.Exists(userPath))
{
// Delete together with all contents
Directory.Delete(userPath, recursive: true);
Console.WriteLine("User folder deleted!");
}
else
{
Console.WriteLine("Folder already does not exist.");
}
}
5. Table: Main methods for working with folders
| Operation | Method | Notes |
|---|---|---|
| Create folder | |
Recursively creates all folders along the path |
| Check existence | |
Returns true or false |
| Delete empty folder | |
Throws if the folder is not empty |
| Delete folder with contents | |
Irreversibly wipes everything inside |
| Get list of files | |
Returns file names |
| Get list of subfolders | |
Returns directory names |
6. Non-obvious points and common mistakes
Error when creating: no rights or invalid path
If you try to create a folder in system directories (for example, "C:\Windows\System32\SuperApp"), you'll likely get UnauthorizedAccessException or IOException.
Practical tips:
Always handle errors with try-catch when working with external folders (e.g., on a user's flash drive or a network share).
Don't trust raw user-provided paths blindly.
try
{
Directory.CreateDirectory(pathFromUser);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to create folder: {ex.Message}");
}
Deleting a folder if it's used by another process
If someone (or your own program) has a file from the folder open, attempting to delete the folder will throw IOException — "cannot delete, folder is in use". Close all files inside the folder first.
The directory is not empty and you forgot about recursive: true
Very common issue. If you don't pass recursive: true and the folder is not empty — you'll get an exception.
Use absolute paths for critical operations
Working with relative paths ("Reports") is always relative to the application's current working directory. If the program is started from somewhere else, the folder will be created in an unexpected place. Check where your code is running from, or provide a full path right away:
string fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyAppData");
Directory.CreateDirectory(fullPath);
GO TO FULL VERSION