How can I delete the contents a directory, without deleting the directory itself? Here's what I've tried so far

StackOverflow https://stackoverflow.com/questions/23574885

  •  19-07-2023
  •  | 
  •  

Question

I'm making a button that reads a file path then deletes the files within the folder. It's currently deleting the entire directory. Here's my code:

public void deleteFiles(string Server)
{
    string output = "\\\\" + Server + "\\F\\Output";
    string input = "\\\\" + Server + "\\F\\Input";
    string exceptions = "\\\\" + Server + "\\F\\Exceptions";

    new System.IO.DirectoryInfo(input).Delete(true);
    new System.IO.DirectoryInfo(output).Delete(true);
    new System.IO.DirectoryInfo(exceptions).Delete(true);
}
Was it helpful?

Solution 2

Would just deleting the directory and recreating it work? Or do you want to preserve permissions?

OTHER TIPS

You are calling Delete method on DirectoryInfo, you should call it on FileInfo's instead:

var files =  new DirectoryInfo(input).GetFiles()
                .Concat(new DirectoryInfo(output).GetFiles())
                .Concat(new DirectoryInfo(exceptions).GetFiles());

foreach(var file in files)
     file.Delete();

Another way:

var files =  Directory.GetFiles(input)
                .Concat(Directory.GetFiles(output))
                .Concat(Directory.GetFiles(exceptions));

foreach(var file in files)
     File.Delete(file);

DirectoryInfo.Delete and Directory.Delete delete empty directories, if you want to delete files you could try this method:

public void DeleteFiles(string path, bool recursive, string searchPattern = null)
{
    var entries = searchPattern == null ? Directory.EnumerateFileSystemEntries(path) : Directory.EnumerateFileSystemEntries(path, searchPattern);
    foreach(string entry in entries)
    {
        try
        {
            FileAttributes attr = File.GetAttributes(entry);
            //detect whether its a directory or file
            bool isDir = (attr & FileAttributes.Directory) == FileAttributes.Directory;
            if(!isDir)
                File.Delete(entry);
            else if(recursive)
                DeleteFiles(entry, true, searchPattern);
        }
        catch
        {
            //ignore
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top