Delete files from multiple folders quickly and easily in C#


[delete files]

The example Delete files quickly and easily in C# lets you make a list of files matching a pattern, check the files that you want deleted, and then delete them all quickly. Reader Uldis posted a comment asking how to do something similar if the files are in multiple folders. That’s what this example does.

Enter the folders that the program should search in the upper text box, type a pattern to search for, and click List Files. The program searches the folders that you listed for files with names that match the pattern and displays the results in a CheckedListBox. Select the files that you want to delete and click Delete to delete them.

Warning: The files are permanently deleted, so be sure you really want to delete them. If you want to move them into the recycle bin instead, see my post Manage the recycle bin (wastebasket) in C#.


Also note that I have tested this program and I believe it works, but you may want to do additional testing and even when it works you should be very careful. This program could do a lot of damage to your system very quickly.

Looping through the folders looking for files with names that match a pattern isn’t too hard. The trickier issue is making ensuring that each file only appears in the CheckedListBox once. For example, suppose you search the folders C:\MyFiles and C:\MyFiles\Tests, and the second folder contains the file Target.txt. When the program searches the two folders, it will find the file twice.

If the program includes the file in the CheckedListBox twice, then it might try to delete the file twice. That will cause an error when the program tries to delete the already deleted file a second time. Even worse, what if you check one of the entries and not the other? Should the program delete the file or shouldn’t it?

To avoid these issues, the program includes any file in the CheckedListBox only once.

The following code shows how the program lists the files that match the pattern you entered.

// List the selected files.
private void btnListFiles_Click(object sender, EventArgs e)
{
    clbFiles.Items.Clear();

    // Loop through the folders.
    char[] separators = { '\r', '\n' };
    string[] folders = txtFolders.Text.Split(
        separators, StringSplitOptions.RemoveEmptyEntries);
    foreach (string folder in folders)
    {
        // Find files in this folder.
        try
        {
            DirectoryInfo dir_info = new DirectoryInfo(folder);
            foreach (FileInfo file_info in dir_info.GetFiles(
                txtPattern.Text, SearchOption.AllDirectories))
            {
                string file_name = file_info.FullName;
                if (clbFiles.Items.Contains(file_name))
                    Console.WriteLine("Skipped " + file_name);
                else
                    clbFiles.Items.Add(file_name);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    // Check all items.
    for (int i = 0; i < clbFiles.Items.Count; i++)
        clbFiles.SetItemChecked(i, true);
    lblNumFiles.Text = clbFiles.Items.Count + " files";
    btnDelete.Enabled = clbFiles.CheckedIndices.Count > 0;
}

This code first clears the CheckedListBox. It then splits the text containing the folder names at newline and carriage return characters and loops through the folder names.

For each folder, the code uses the DirectoryInfo class’s GetFiles method to find files within the folder’s directory hierarchy that match the pattern that you entered. For each matching file, it determines whether the CheckedListBox already contains that file’s full name. If the file is not already in the list, the code adds it.

After it has listed all of the files, the method checks all of the items in the CheckedListBox.

The rest of the program is similar to the previous example. See that post and download the example program to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in files, system and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.