Delete all folders in parent folder except where sub folder contains specific file

时间:2018-10-02 09:10:40

标签: c#

I'm having problems keeping 1 folder which contains an image I want to keep.

I'm currently using the code below:

DirectoryInfo di = new DirectoryInfo(pathToMedia);
foreach (var image in di.GetFiles())
        {
            if (!image.Name.Contains(emailImage))
               {
                 di.Delete(true);
               }
         } 

The above does not work as I cannot seem to get the file name of the image inside the sub-folder, any help would be appreciated

1 个答案:

答案 0 :(得分:0)

代码无法找到文件,因为GetFiles(string)方法仅返回当前目录中的文件,而不返回子文件夹中的文件(存在允许获取所有文件的重载,但这将无济于事在这里,因为我们也需要目录信息)。如果要检查所有子文件夹中的文件,则必须递归地遍历整个结构。

下面的代码显示了如何执行此操作,在这种情况下,您无需检查控制台是否与要搜索的文件相匹配,而无需编写控制台。

您可以在api documentation中查看有关这些方法的详细信息 如文档中所述,如果您的文件夹中包含大量文件,使用EnumerateFiles可能对您有益。

// Process all files in the directory passed in, recurse on any directories 
    // that are found, and process the files they contain.
    public static void ProcessDirectory(string targetDirectory) 
    {
        // Process the list of files found in the directory.
        string [] fileEntries = Directory.GetFiles(targetDirectory);
        foreach(string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.
        string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach(string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }

    // Insert logic for processing found files here.
    public static void ProcessFile(string path) 
    {
        Console.WriteLine("Processed file '{0}'.", path);       
    }