Directory
The Directory class deals with folders: making them, checking they exist, and listing what is inside. It is like a caretaker for your filing cabinets.
In this page:
Syntax
Directory.CreateDirectory(path);
Directory.Exists(path);
string[] files = Directory.GetFiles(path);
Directory.Delete(path);
Directory
The Directory class provides static methods for creating, checking, listing, and deleting folders, such as Directory.CreateDirectory and Directory.Exists.
Directory.GetFiles returns the files inside a folder as an array of paths. It's the folder-level counterpart to the file-level File class.
Note:
Directory.CreateDirectory does nothing (and doesn't throw) if the directory already exists.Example: Directory
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string folder = "reports";
Directory.CreateDirectory(folder);
Console.WriteLine(Directory.Exists(folder));
File.WriteAllText(Path.Combine(folder, "a.txt"), "data");
string[] files = Directory.GetFiles(folder);
foreach (string f in files)
{
Console.WriteLine(f);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Calling
Directory.Delete(path)on a folder that still has files, which throws anIOException; passtrueas the second argument to delete its contents too. - Calling
Directory.GetFileson a folder that does not exist, which throws aDirectoryNotFoundException; checkDirectory.Existsfirst. - Assuming a relative path like
"reports"is next to the source file, when it is relative to the program's current working directory.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: