简体   繁体   English

C#使用过滤器删除文件夹中的文件

[英]C# delete files in folder with filter

I am using SharpDevelop to write a C# program (not console). 我正在使用SharpDevelop编写C#程序(而不是控制台)。 I want to delete files within a specified directory, but be able to EXCLUDE files beginning, ending, or containing certain words. 我想删除指定目录中的文件,但是能够排除文件开头,结尾或包含某些单词的文件。

TO completely delete ALL files in a folder I am using this : 要完全删除文件夹中的所有文件,我正在使用:

private void clearFolder(string FolderName)
{
    DirectoryInfo dir = new DirectoryInfo(FolderName);

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

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        clearFolder(di.FullName);
        di.Delete();
    }
}

I use it like 我用它像

ClearFolder("NameOfFolderIWantToEmpty");

Is there a way to modify this so that I can delete all files and direcotries EXCEPT those files and directories containing specific words? 有什么方法可以修改此设置,以便除包含特定单词的文件和目录外,我还可以删除所有文件和目录?

Something like : 就像是 :

CleanFolder(FolderToEmpty,ExcludeAllFileAndDirectoriesContaingThisPhrase);

so that if I did 这样我就可以了

CleanFolder("MyTestFolder","_blink");

It would NOT delete files and directories with names like 它不会删除名称如下的文件和目录

_blinkOne (file)

Test_blineGreen (file)

Test_blink5 (directory)

_blinkTwo (file within the Text_blink5 directory)

Folder_blink (empty directory)

but WOULD delete files and directories like 但会删除文件和目录,例如

test (file)

test2 (directory)

test3_file (file within test2 directory)

test4 (empty directory)

I suspect I might have to iterate through each file and directory, checking them one at a time for the matching filter and deleting it if it does not match, but I am not sure how to do that. 我怀疑我可能必须遍历每个文件和目录,一次检查一次它们是否匹配过滤器,如果不匹配则将其删除,但是我不确定该怎么做。

Something with FileInfo() and DirectoryInfo() perhaps? 也许与FileInfo()DirectoryInfo()

Can somebody help by providing a working example? 有人可以通过提供一个有效的例子来提供帮助吗? (modified version of the above is preferred, but if a new method is required, as long as it doesn't require an outside dll, is OK. (最好使用上述方法的修改版本,但如果需要一种新方法,只要它不需要外部dll,就可以。

Use the Directory.GetFiles(string, string) method to get a list of files that match your pattern, and use Enumerable.Except(IEnumerable<T>) to get the files you actually want to delete. 使用Directory.GetFiles(string, string)方法获取您的模式匹配的文件列表,并使用Enumerable.Except(IEnumerable<T>)获取您实际上要删除的文件。

string pattern = *.*;
var matches = Directory.GetFiles(folderName, pattern);
foreach(string file in Directory.GetFiles(folderName).Except(matches))
    File.Delete(file);

There's no need to use DirectoryInfo here, since you appear to be concerned only with manipulating the files in the directory. 此处无需使用DirectoryInfo,因为您似乎只关心操作目录中的文件。

Just test to see if the FileInfo.Name property (string) StartsWith or EndsWith a specified string. 只需测试看看FileInfo.Name属性(字符串)是否为StartsWithEndsWith指定的字符串即可。

    foreach (FileInfo fInfo in di.GetFiles())
    {
        if (!fInfo.Name.StartsWith("AAA") || 
            !fInfo.Name.EndsWith("BBB"))
        {
            fInfo.Delete();
        }
    }

Or if you are looking for a word anywhere in the filename, use the Contains method: 或者,如果您要在文件名中的任何位置查找单词,请使用Contains方法:

    foreach (FileInfo fInfo in di.GetFiles())
    {
        if (!fInfo.Name.Contains("CCC")) 
        {
            fInfo.Delete();
        }
    }
if(!fi.Name.Contains("_blink"))
      fi.Delete();

I think I have a solution that will work for me. 我认为我有一个适合我的解决方案。 Posting the full code here so that others may use it, tweak it, and/or examine it for possible flaws. 将完整的代码发布到此处,以便其他人可以使用它,对其进行调整和/或检查其可能的漏洞。 This is my first time using StackOverFlow, and knowing that I have this resource available to search and the ability to ask questions and people can actually help, is a great comfort to me as a person who is new to all of this stuff. 这是我第一次使用StackOverFlow,并且知道我拥有可供搜索的资源以及能够提出问题且人们可以提供实际帮助的能力,这对我来说是一个极大的安慰,因为他是所有这些内容的新手。

Thanks a ton everybody! 谢谢大家!

// Search directory recursively and delete ALL sub-directories and files //递归搜索目录并删除所有子目录和文件

// with names that do NOT contain the given search pattern //名称不包含给定搜索模式的名称

private void clearFolderWithFilter(string folderName, string filesToExclude)
{
    DirectoryInfo dir = new DirectoryInfo(folderName);

    foreach(FileInfo fi in dir.GetFiles())
    {
        if(!fi.Name.Contains(filesToExclude))
        {
            // System.Diagnostics.Debug.WriteLine("DELETING file " + fi + " because it does NOT contain '" + filesToExclude + "' ");
            fi.Delete();
        } else {
            // System.Diagnostics.Debug.WriteLine("SAVING file " + fi + " because it contains '" + filesToExclude + "' ");
        }
    }

    foreach (DirectoryInfo di in dir.GetDirectories())
    {
        if(!di.Name.Contains(filesToExclude))
        {
            // System.Diagnostics.Debug.WriteLine("DELETING directory " + di + " because it does NOT contain '" + filesToExclude + "' ");
            clearFolderWithFilter(di.FullName, filesToExclude);
            di.Delete();
        } else {
            // System.Diagnostics.Debug.WriteLine("SAVING directory " + di + " because it contains '" + filesToExclude + "' ");
        }
    }
}

Usage : 用法:

clearFolderWithFilter(@"C:\Path\MyFolder","DoNotDelete_");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM