C-SHARP - 5.6 Exercice

This end-of-section exercise consolidates working with files and directories in C#, covered in the previous lessons. It brings together the File, Directory, and Path classes along with loops and conditions.

Exercise

Write a program that asks the user for a folder path, then:

  • checks that the folder exists (otherwise displays an error);
  • lists every file in that folder along with its name, extension, and size;
  • creates a subfolder named "archives" inside it;
  • copies every .txt file found into that new subfolder.

Suggested solution

Use Directory.Exists to check, Directory.GetFiles to list, Path.GetExtension to filter by extension, Path.Combine to build the destination paths, and File.Copy for the actual copy:

using System.IO;

Console.Write("Folder path: ");
string folder = Console.ReadLine();

if (!Directory.Exists(folder))
{
    Console.WriteLine("The folder does not exist.");
    return;
}

string archives = Path.Combine(folder, "archives");
Directory.CreateDirectory(archives);

foreach (string file in Directory.GetFiles(folder))
{
    FileInfo info = new FileInfo(file);
    Console.WriteLine($"{info.Name} ({info.Extension}, {info.Length} bytes)");

    if (Path.GetExtension(file) == ".txt")
    {
        string destination = Path.Combine(archives, info.Name);
        File.Copy(file, destination, overwrite: true);
    }
}

This exercise combines almost every notion from the section: existence checks, reading file information, creating a directory, filtering by extension, and targeted copying. If you're comfortable with this program, you've mastered the essentials of file handling in C#. The next section moves on to more advanced topics.