Working with Directories in C# โ Create, Delete & Manage
๐ Introduction
Hey there, coder! ๐ Have you ever had tons of files cluttering your desktop? Imagine your downloads folder is a mess, filled with random PDFs, images, and videos. Wouldn’t it be awesome to organize everything into separate folders automatically?
Well, thatโs exactly what weโll learn today! ๐คฉ
With Working with Directories in C#, you can create, delete, move, and list folders dynamically. Whether you’re building a file manager, a backup system, or just organizing your project files, handling directories is a must-have skill.
So, letโs clean up that digital mess and start coding! ๐
๐ What You Are Going to Learn in This Lesson
โ๏ธ How to create directories using Directory.CreateDirectory()
โ๏ธ How to delete directories using Directory.Delete()
โ๏ธ How to move directories using Directory.Move()
โ๏ธ How to list directories and files inside them
โ๏ธ Real-world examples with complete code and outputs
Let’s jump right in! ๐ฏ
๐ How to Create a Directory in C#
Creating a folder is super simple in C#. Just use Directory.CreateDirectory()
.
ย
๐ Example 1: Creating a Directory
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = "MyNewFolder";
// Create directory if it doesn't exist
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
Console.WriteLine("Folder created successfully!");
}
else
{
Console.WriteLine("Folder already exists!");
}
}
}
๐ฅ๏ธ Output:
Folder created successfully!
๐ Explanation:
1๏ธโฃ We define the folder name MyNewFolder
.
2๏ธโฃ Before creating it, we check if it already exists using Directory.Exists()
.
3๏ธโฃ If it doesn’t exist, we create it using Directory.CreateDirectory()
.
Simple, right? ๐
๐๏ธ How to Delete a Directory in C#
Need to remove an empty folder? Use Directory.Delete()
.
ย
๐ Example 2: Deleting a Directory
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = "MyOldFolder";
// Create the folder first
Directory.CreateDirectory(folderPath);
// Delete folder if it exists
if (Directory.Exists(folderPath))
{
Directory.Delete(folderPath);
Console.WriteLine("Folder deleted successfully!");
}
else
{
Console.WriteLine("Folder not found!");
}
}
}
๐ฅ๏ธ Output:
Folder deleted successfully!
โ ๏ธ Warning:
ย Directory.Delete()
only works if the folder is empty. If it has files, you’ll need to delete them first!
๐ฆ How to Move a Directory in C#
Want to move a folder? Just use Directory.Move()
.
ย
๐ Example 3: Moving a Directory
using System;
using System.IO;
class Program
{
static void Main()
{
string sourceFolder = "SourceFolder";
string destinationFolder = "MovedFolder";
// Create source folder
Directory.CreateDirectory(sourceFolder);
// Move the folder
if (Directory.Exists(sourceFolder))
{
Directory.Move(sourceFolder, destinationFolder);
Console.WriteLine("Folder moved successfully!");
}
else
{
Console.WriteLine("Source folder not found!");
}
}
}
๐ฅ๏ธ Output:
Folder moved successfully!
๐ Explanation:
1๏ธโฃ We create a folder called SourceFolder.
2๏ธโฃ We check if it exists before moving.
3๏ธโฃ Directory.Move(source, destination)
moves it to MovedFolder.
Now, the old folder is gone, and its contents are in the new location. Neat, right? ๐คฉ
๐ How to List Directories and Files
Letโs say you want to list all files and folders inside a directory. Use Directory.GetFiles()
and Directory.GetDirectories()
.
ย
๐ Example 4: Listing Files and Directories
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = "MyDocuments";
// Create folder and sample files
Directory.CreateDirectory(folderPath);
File.WriteAllText(Path.Combine(folderPath, "file1.txt"), "Hello!");
File.WriteAllText(Path.Combine(folderPath, "file2.txt"), "C# is fun!");
// List all files
Console.WriteLine("Files in the folder:");
foreach (var file in Directory.GetFiles(folderPath))
{
Console.WriteLine(file);
}
// List all directories
Console.WriteLine("Subdirectories:");
foreach (var dir in Directory.GetDirectories(folderPath))
{
Console.WriteLine(dir);
}
}
}
๐ฅ๏ธ Output:
Files in the folder:
MyDocuments\file1.txt
MyDocuments\file2.txt
Subdirectories:
๐ Real-World Scenario: Organizing Project Files
Letโs say you’re working on a C# project. Your files are all over the placeโsource code, images, logs, and reports. You want to automatically organize them into proper folders.
ย
๐ Example: Auto-Sorting Files into Directories
using System;
using System.IO;
class Program
{
static void Main()
{
string baseFolder = "ProjectFiles";
string imagesFolder = Path.Combine(baseFolder, "Images");
string docsFolder = Path.Combine(baseFolder, "Documents");
// Create folders if they don't exist
Directory.CreateDirectory(imagesFolder);
Directory.CreateDirectory(docsFolder);
// Sample files
string[] files = { "pic1.jpg", "report.pdf", "pic2.png", "notes.docx" };
foreach (var file in files)
{
string destinationFolder = file.EndsWith(".jpg") || file.EndsWith(".png") ? imagesFolder : docsFolder;
string destinationPath = Path.Combine(destinationFolder, file);
File.WriteAllText(destinationPath, "Sample content");
Console.WriteLine($"{file} moved to {destinationFolder}");
}
}
}
๐ฅ๏ธ Output:
pic1.jpg moved to ProjectFiles\Images
report.pdf moved to ProjectFiles\Documents
pic2.png moved to ProjectFiles\Images
notes.docx moved to ProjectFiles\Documents
Now, files are automatically sorted into folders based on type! ๐
๐ Conclusion
Wow! You just mastered Working with Directories in C#! ๐
๐น Create folders using Directory.CreateDirectory()
.
๐น Delete folders using Directory.Delete()
.
๐น Move folders using Directory.Move()
.
๐น List files and subdirectories using Directory.GetFiles()
and Directory.GetDirectories()
.
This knowledge will supercharge your file-handling skills! Try it out, experiment, and have fun! ๐
ย
โญ๏ธ Next What?
You’re now a pro at Working with Directories in C#! But what if you need to manipulate file paths, get file extensions, or extract folder names? ๐ค
In the next chapter, youโll learn Path Class in C#! Stay tuned and keep coding! ๐