Complete C# Tutorial

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! ๐Ÿš€

๐Ÿ“‚ 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! ๐Ÿš€

Leave a Comment

Share this Doc

Working with Directories

Or copy link