2009-06-12 76 views
9

也就是說,刪除指定目錄目錄中的匹配模式如何刪除文件

例中的匹配模式的所有文件,刪除內的DirectoryName

所有* .jpg文件
+0

你可以使用正則表達式。做一些Google模式匹配,RegEx不是我的專長,但他們是強大的地獄。 – 2009-06-12 20:05:24

+2

(文件API通常不支持正則表達式,只是普通的通配符。完整的regex是外殼和腳本語言更多的東西) – 2009-06-12 20:42:57

回答

22
procedure TForm1.Button1Click(Sender: TObject); 
begin 
    DeleteFiles(ExtractFilePath(ParamStr(0)),'*.jpg'); 
end; 

procedure DeleteFiles(APath, AFileSpec: string); 
var 
    lSearchRec:TSearchRec; 
    lPath:string; 
begin 
    lPath := IncludeTrailingPathDelimiter(APath); 

    if FindFirst(lPath+AFileSpec,faAnyFile,lSearchRec) = 0 then 
    begin 
    try 
     repeat 
     SysUtils.DeleteFile(lPath+lSearchRec.Name);  
     until SysUtils.FindNext(lSearchRec) <> 0; 
    finally 
     SysUtils.FindClose(lSearchRec); // Free resources on successful find 
    end; 
    end; 
end; 
+0

(有沒有必要fillchar的lsearchrec)所有 – 2009-06-12 20:46:10

5

您可以使用SHFileOperation功能。關於使用SHFileOperation的好處是,你必須將文件刪除到回收站的選項,你會得到正常的API動畫,這樣用戶就知道是怎麼回事。缺點是刪除將比Jeff的代碼稍長一些。

有幾種包裝在那裏。我使用了BP Software的這個免費包裝。整個包裝文件只有220行,易於閱讀和使用。我不會將其作爲組件安裝。我發現將這個單元添加到我的項目中很簡單,只需根據需要創建並釋放對象。

更新:下載鏈接BP軟件的網站不再有效。有一個older version on the Embarcadero website

TSHFileOp(1.3.5.1)(3 KB) 31日,2006年
TComponent是一個包裝 爲SHFileOperation API複製, 移動,重命名或刪除(有 回收斌支持
五月)文件系統 對象。

SHFileOperation的文件名參數支持MS DOS樣式通配符。所以,你可以使用該組件是這樣的:


     FileOps := TSHFileOp.Create(self); 

     FileOps.FileList.Add(DirectoryName + '\*.jpg'); 

     FileOps.HWNDHandle := self.Handle; 
     FileOps.Action := faDelete; 
     FileOps.SHOptions := 
      [ofAllowUndo, ofNoConfirmation, ofFilesOnly, ofSimpleProgress]; 
     FileOps.Execute; 

我通常顯示「你確定」的消息自己,所以我總是通過ofNoConfirmation標誌,以便Windows不會再問。

如果你不想刪除所有的JPG文件,或者您需要從多個目錄中刪除,你可以到文件列表中的字符串列表調用execute之前,外卡添加完整的文件名或不同的路徑。

這是MSDN Page for SHFileOperation
請注意,SHFileOperation已被從Windows Vista開始的IFileOperation取代。我繼續在Windows Vista上使用SHFileOperation,沒有任何問題。

4

在較新版本的Delphi,你可能會使用在System.IOUtils的類,它基本上包裝FindFirstFindNext等:

procedure DeleteFilesMatchingPattern(const Directory, Pattern: string); 
    var FileName: string; 
begin 
    for FileName in TDirectory.GetFiles(Directory, Pattern) do TFile.Delete(FileName); 
end; 
相關問題