Delete files quickly and easily in C#

[delete files]

A while ago, I needed to delete files that were created when I opened old projects in a newer version of Visual Studio. LOTS of files. (As far as I know, there’s no way to tell Visual Studio not to create these files.)

I don’t know why, but Windows Explorer was taking several seconds to delete each file and there were almost a hundred, so the whole thing was taking far too long. Rather than waiting the 5 or so minutes it would have taken to delete them all, I wrote this program to delete the files. (This probably took longer than waiting for Windows Explorer to do the job but it was more interesting and if this happens again I’ll have the program ready.)

Enter a directory path and a pattern to match and click List Files to see a list of the files matching the pattern in the directory you entered and its subdirectories. Initially all of the matching files are checked in the CheckedListBox. Review the list to make sure you want to delete the files, uncheck any that you want to keep, and click Delete to make the files go away forever.

If you want to move the files into the recycle bin instead of permanently deleting them, see my post Manage the recycle bin (wastebasket) in C#.

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)
        DirectoryInfo dir_info = new DirectoryInfo(txtPath.Text);
        foreach (FileInfo file_info in dir_info.GetFiles(
            txtPattern.Text, SearchOption.AllDirectories))
            int index = clstFiles.Items.Add(file_info.FullName);
            clstFiles.SetItemChecked(index, true);
        lblNumFiles.Text = clstFiles.Items.Count + " files";
        btnDelete.Enabled = clstFiles.CheckedIndices.Count > 0;
    catch (Exception ex)

The code starts by clearing the CheckedListBox. It then creates a DirectoryInfo object representing the directory path that you entered. It uses that object’s GetFiles method to get a collection of FileInfo objects representing the files matching the pattern that you entered.

The program adds each file’s name to the CheckedListBox and checks it. The code uses the index of the newly added file to check it instead of simply checking the last item in the list because the control’s Sorted property is set to true so the new file may not be added to the end of the list. (Alternatively, you could add all of the files and then check them all afterwards.)

This piece of code finishes by displaying the number of files listed and enabling the Delete button.

The following code shows how the program deletes the checked files.

// Delete the checked files.
private void btnDelete_Click(object sender, EventArgs e)
    string[] filenames = new string[clstFiles.CheckedItems.Count];
    clstFiles.CheckedItems.CopyTo(filenames, 0);
    foreach (string filename in filenames)
        catch (Exception ex)
            Console.WriteLine("Error deleting file. " + ex.Message);
            if (MessageBox.Show("Error deleting file. " + ex.Message +
                Environment.NewLine + Environment.NewLine +
                "Continue?", "Continue?",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == DialogResult.No)

    lblNumFiles.Text = clstFiles.CheckedItems.Count + " files";
    btnDelete.Enabled = clstFiles.CheckedItems.Count > 0;

Normally, if you just want to loop through the checked items in a CheckedListBox, you can iterate over its CheckedItems collection. However, this example removes files from the CheckedListBox as they are deleted. A C# program cannot modify a collection while it is iterating over it, so this code first copies the file names into an array. It then loops through the array so it can remove items from the CheckedListBox with no problems.

As it loops through the file names, the code displays the name in the Console window. It uses File.Delete to permanently delete the file and then removes the file name from the CheckedListBox.

If anything goes wrong, the code displays a MessageBox telling you what the problem is and asking if you want to continue. If you click No, the code breaks out of the loop. I figure if something goes wrong, then it might happen a lot of times. For example, if you don’t have delete permission on a directory containing hundreds of files, the program may fail hundreds of times and it could take you a while to close each MessageBox separately. This gives you a way to stop the process.

Download Example   Follow me on Twitter   RSS feed   Donate


4 Responses to Delete files quickly and easily in C#

  1. Uldis says:

    Thank you!
    Good job!
    How would the code look like if Path is multi line?
    I mean to specify multiple directories?

    • RodStephens says:

      This example already searches the directory and its sub-directories, so it can handle that situation.

      If you want to list files to delete in multiple directories that are not in a hierarchy, you could use a multi-line text box to let the user enter the directories. Then when you click List Files, the program would loop through them and add then to the list.

      It might be worth checking that you don’t add the same file to the list twice so the program doesn’t become confused trying to delete an already deleted file. And it’s not clear how the program should handle it if you check the file once and leave it unchecked in another spot.

      I’ll try to post an example in a day or two.

  2. Pingback: Delete files from multiple folders quickly and easily in C# - C# HelperC# Helper

Leave a Reply

