簡體   English   中英

使用Directory.GetFiles與類似regex的過濾器

[英]Using Directory.GetFiles with regex-like filter

我有一個包含兩個文件的文件夾:

  • Awesome.File.20091031_123002.txt
  • Awesome.File.Summary.20091031_123152.txt

此外,第三方應用程序處理文件如下:

  • 從數據庫中讀取folderPathsearchPattern
  • 執行Directory.GetFiles(folderPath, searchPattern) ,處理批量匹配過濾器的任何文件,然后將文件移動到存檔文件夾。

事實證明,我必須將我的兩個文件移動到不同的存檔文件夾中,因此我需要通過提供不同的searchPatterns來單獨選擇它們來單獨處理它們。 請注意,我無法修改第三方應用程序,但我可以修改數據庫中的searchPattern和文件目標。

什么searchPattern將允許我選擇Awesome.File.20091031_123002.txt而不包括Awesome.File.Summary.20091031_123152.txt

如果你打算使用LINQ那么......

  var regexTest = new Func<string, bool>(i => Regex.IsMatch(i, @"Awesome.File.(Summary)?.[\d]+_[\d]+.txt", RegexOptions.Compiled | RegexOptions.IgnoreCase));
  var files = Directory.GetFiles(@"c:\path\to\folder").Where(regexTest);

Awesome.File.????????_??????.txt

問號(?)充當單個字符占位符。

我想在這里嘗試我微薄的linq技能......我確信有一個更優雅的解決方案,但這是我的:

string pattern = ".SUMMARY.";
string[] awesomeFiles = System.IO.Directory.GetFiles("path\\to\\awesomefiles");

        IEnumerable<string> sum_files = from file in awesomeFiles
                                        where file.ToUpper().Contains(pattern)
                                        select file;

        IEnumerable<string> other_files = from file in awesomeFiles
                                        where !file.ToUpper().Contains(pattern)
                                        select file;

這假設目錄中除了兩個文件之外沒有任何其他文件,但您可以在此處調整模式以滿足您的需要(即將“Awesome.File”添加到模式開始。)

當你迭代每個集合時,你應該得到你需要的東西。

根據文檔searchPattern只支持*****和 通配符。 您需要編寫自己的正則表達式過濾器,該過濾器獲取Directory.GetFiles的結果並應用進一步的過濾邏輯。

如果你不想使用Linq,這是一種方法。

public void FileChecker(string filePath)
{
    DirectoryInfo di = new DirectoryInfo(filePath);
    int _MatchCounter;
    string RegexPattern = "^[a-zA-Z_a-zA-Z_a-zA-Z_0-9_0-9_0-9.csv]*$";
    Regex RegexPatternMatch = new Regex(RegexPattern, RegexOptions.IgnoreCase);

    foreach (FileInfo matchingFile in di.GetFiles())
    {
        Match m = RegexPatternMatch.Match(matchingFile.Name);

        if ((m.Success))
        {
            MessageBox.Show(matchingFile.Name);
            _MatchCounter += 1;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM