[C#] Creating, Deleting, and Moving Directories (Folders)

In addition to files, you can manage directories (folders) using the static methods of the System.IO.Directory class. In particular, the CreateDirectory method is very convenient because it automatically creates any missing parent folders in the specified path.

目次

Implementation Sample: Organizing Project Folders

The following code demonstrates a scenario for managing project work folders. It follows a flow of checking for an existing folder, deleting it to reset the workspace, and finally renaming it to archive the project.

Sample Code

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        // Target directory paths
        // These will be handled automatically even if they include deep levels
        string workDir = Path.Combine("Projects", "2025", "WorkSpace");
        string archiveDir = Path.Combine("Projects", "2025", "Finished_Project");

        Console.WriteLine($"Work Folder: {workDir}");

        // 1. Check existence (Directory.Exists)
        if (Directory.Exists(workDir))
        {
            Console.WriteLine("Existing folder found. Cleaning up...");

            // 2. Delete directory (Directory.Delete)
            // Setting the second argument 'recursive' to true deletes all files and subfolders
            // If false, an error occurs if the folder is not empty
            Directory.Delete(workDir, recursive: true);
            
            Console.WriteLine("Deletion complete.");
        }
        else
        {
            Console.WriteLine("Folder does not exist yet.");
        }

        // 3. Create directory (Directory.CreateDirectory)
        // Even if 'Projects' or '2025' folders do not exist, they are all created automatically
        Directory.CreateDirectory(workDir);
        Console.WriteLine("New folder created.");

        // Create a dummy file inside
        File.WriteAllText(Path.Combine(workDir, "readme.txt"), "Project Data");

        // 4. Move or Rename directory (Directory.Move)
        // It is recommended to check the destination first, as an error occurs if it already exists
        if (!Directory.Exists(archiveDir))
        {
            Directory.Move(workDir, archiveDir);
            Console.WriteLine($"Folder renamed (moved) to: \n -> {archiveDir}");
        }
    }
}

Execution Result

Work Folder: Projects\2025\WorkSpace
Folder does not exist yet.
New folder created.
Folder renamed (moved) to: 
 -> Projects\2025\Finished_Project

Explanation and Technical Points

1. Directory.CreateDirectory

This is a very powerful method. Similar to the mkdir -p command in Linux, it creates all necessary directory levels in the specified path. If the directory already exists, it does nothing and does not throw an error.

2. Recursive Deletion with Directory.Delete

By using Directory.Delete(path, true), you can forcibly delete a folder that contains files or subfolders. Warning: Be extremely careful when specifying paths; accidentally deleting an important parent folder (such as C:\Windows) can cause critical damage to your system.

3. Directory.Move

Both moving a folder to a different location and renaming a folder are performed using this method.

  • Limitations: If a folder with the same name already exists at the destination path, an IOException will occur (you cannot overwrite an existing folder).
  • Moving Across Drives: You can move folders between different volumes, such as from the C drive to the D drive. Internally, this is handled by a copy-and-delete process.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次