C# Directories
A directory is a folder that holds files. The Directory and Path classes create folders and build file paths.
Create a folder
CreateDirectory makes the folder. Exists then answers true for it and false for a folder never made.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
Directory.CreateDirectory("data");
Console.WriteLine("Data folder: " + Directory.Exists("data"));
Console.WriteLine("Other folder: " + Directory.Exists("other"));
}
}Combine path parts
Path.Combine joins a folder name and a file name. The joined path uses a forward slash on this system.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = Path.Combine("data", "notes.txt");
Console.WriteLine(path);
string deep = Path.Combine("data", "2026", "notes.txt");
Console.WriteLine(deep);
}
}List file names sorted
GetFiles finds the files inside the folder. The names are sorted before printing, so no full path appears.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
Directory.CreateDirectory("data");
File.WriteAllText(Path.Combine("data", "b.txt"), "b");
File.WriteAllText(Path.Combine("data", "a.txt"), "a");
string[] files = Directory.GetFiles("data");
string[] names = new string[files.Length];
for (int i = 0; i < files.Length; i++)
{
names[i] = Path.GetFileName(files[i]);
}
Array.Sort(names);
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}
}
}Example
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
Directory.CreateDirectory("archive");
string first = Path.Combine("archive", "one.txt");
string second = Path.Combine("archive", "two.txt");
File.WriteAllText(first, "1");
File.WriteAllText(second, "2");
Console.WriteLine("Folder: " + Directory.Exists("archive"));
Console.WriteLine("Path: " + second);
string[] files = Directory.GetFiles("archive");
string[] names = new string[files.Length];
for (int i = 0; i < files.Length; i++)
{
names[i] = Path.GetFileName(files[i]);
}
Array.Sort(names);
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}
}
}Key points
- using System.IO brings in the Directory and Path classes.
- Directory.CreateDirectory creates a new folder.
- Directory.Exists answers true when a folder is there.
- Path.Combine joins path parts into one string.
- Combine inserts the separator used by the current system.
- Directory.GetFiles returns the paths of the files in a folder.
- Path.GetFileName keeps only the name part of a path.
In this example, the program creates an archive folder and builds two paths with Combine. Both files are written through those paths. The folder check and the combined path print first, and the sorted file names print last.
Note
Sorting the names gives the same print order on every run.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Path.Combine("data", "notes.txt") print on this system?