是否可以使用 FileExistsFileSearch (或任何其他 Pascal 函数)来确定给定文件夹中是否存在文件模式?

例如:

if (FileExists('c:\folder\*.txt') = True) then 

请您参考如下方法:

目前,没有支持通配符检查某个文件是否存在的功能。那是因为 FileExists FileSearch 函数内部使用 NewFileExists 函数,正如源代码中的注释所述,不支持通配符。

幸运的是,还有 FindFirst 它支持通配符,因此您可以为您的任务编写如下函数:

[Code] 
function FileExistsWildcard(const FileName: string): Boolean; 
var 
  FindRec: TFindRec; 
begin 
  Result := False; 
  if FindFirst(FileName, FindRec) then 
  try 
    Result := FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0; 
  finally 
    FindClose(FindRec); 
  end; 
end; 

用法同 FileExists 功能,只是您可以使用通配符进行搜索,例如 lpFileName 的 MSDN 引用描述 FindFirstFile 的参数功能。因此,要检查是否有 txt 的文件 C:\Folder 中的扩展名您可以通过以下方式调用上述函数:

if FileExistsWildcard('C:\Folder\*.txt') then 
  MsgBox('There is a *.txt file in the C:\Folder\', mbInformation, MB_OK); 

当然,要搜索的文件名可能包含文件的部分名称,例如:

if FileExistsWildcard('C:\Folder\File*.txt') then 
  MsgBox('There is a File*.txt file in the C:\Folder\', mbInformation, MB_OK); 

这种模式将匹配文件,例如 C:\Folder\File12345.txt .


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!