删除多个目录中的所有文件和文件夹,但保留目录

时间:2010-06-02 02:56:47

标签: c# delete-file

嗯,我喜欢这段很好的代码,它似乎工作得很棒,但我似乎无法添加任何更多的目录

DirectoryInfo dir = new DirectoryInfo(@"C:\temp"); 

foreach(FileInfo files in dir.GetFiles())
{
    files.Delete();
}

foreach (DirectoryInfo dirs in dir.GetDirectories())
{
    dirs.Delete(true);
}

我还想添加特殊文件夹,例如历史记录和Cookie,以及我将如何进行此操作(我希望包含至少4-5个不同的文件夹)

2 个答案:

答案 0 :(得分:1)

也许这样的事情会有所帮助。我没有测试它。

public void DeleteDirectoryFolders(DirectoryInfo dirInfo){
    foreach (DirectoryInfo dirs in dirInfo.GetDirectories()) 
    { 
        dirs.Delete(true); 
    } 
}

public void DeleteDirectoryFiles(DirectoryInfo dirInfo) {
    foreach(FileInfo files in dirInfo.GetFiles()) 
    { 
        files.Delete(); 
    } 
}

public void DeleteDirectoryFilesAndFolders(string dirName) {
  DirectoryInfo dir = new DirectoryInfo(dirName); 
  DeleteDirectoryFiles(dir)
  DeleteDirectoryFolders(dir)
}

public void main() {
  List<string> DirectoriesToDelete;
  DirectoriesToDelete.add("c:\temp");
  DirectoriesToDelete.add("c:\temp1");
  DirectoriesToDelete.add("c:\temp2");
  DirectoriesToDelete.add("c:\temp3");
  foreach (string dirName in DirectoriesToDelete) {
    DeleteDirectoryFilesAndFolders(dirName);
  }
}

答案 1 :(得分:0)

这是一个递归函数,它将删除给定目录中的所有文件并向下导航目录结构。根据您对另一个答案的评论,可以提供模式字符串以仅处理给定扩展名的文件。

Action<string,string> fileDeleter = null;
fileDeleter = (directoryPath, pattern) =>
{
    string[] files;
    if (!string.IsNullOrEmpty(pattern))
        files = Directory.GetFiles(directoryPath, pattern);
    else
        files = Directory.GetFiles(directoryPath);

    foreach (string file in files)
    {
        File.Delete(file);
    }

    string[] directories = Directory.GetDirectories(directoryPath);
    foreach (string dir in directories)
        fileDeleter(dir, pattern);
};

string path = @"C:\some_folder\";
fileDeleter(path, "*.bmp");

除了目录之外,这显然可以与数组或字符串列表一起使用,以处理多个初始目录路径。

以下是与标准函数重写的相同代码,也将递归作为参数选项。

public void DeleteFilesFromDirectory(string directoryPath, string pattern, bool includeSubdirectories)
{
    string[] files;
    if (!string.IsNullOrEmpty(pattern))
        files = Directory.GetFiles(directoryPath, pattern);
    else
        files = Directory.GetFiles(directoryPath);

    foreach (string file in files)
    {
        File.Delete(file);
    }

    if (includeSubdirectories)
    {
        string[] directories = Directory.GetDirectories(directoryPath);
        foreach (string dir in directories)
            DeleteFilesFromDirectory(dir, pattern, includeSubdirectories);
    }
}