我需要确定哪些文件夹包含“最近”(在一定时间间隔内)修改过的文件。我注意到,每当修改包含的文件时,文件夹日期戳似乎都会更新,但这种行为不会在树上传播,即包含已修改文件的文件夹的日期戳不会更新。

我可以处理这种行为,但我怀疑它取决于平台/文件系统/网络或本地驱动器等。我仍然想尽可能地利用它,因此如果运行我的应用程序的平台/磁盘支持此行为,我需要一个布尔函数来返回 true。

我很高兴能够递归遍历这棵树。我想避免的是必须对每个文件夹中的每个文件执行 FindFirst/FindNext 来查看(比如说)最后一天是否有任何文件被修改 - 如果我可以避免对没有修改日期戳的文件夹执行此操作在最后一天内,这将节省大量时间。

没有正确的解决方案

其他提示

检查 FindFirstChangeNotification FindNextChangeNotification 功能 另一个选项是使用 TJvChangeNotify Jedi组件。

添加,您可以检查此链接

到目前为止已发布的解决方案是在通知发生时获取通知,并且它们可以很好地实现此目的。如果您想回顾过去并查看上次更改某些内容的时间,而不是实时监控它,那么事情就会变得棘手。我认为除了递归搜索文件夹树并检查日期戳之外,没有办法做到这一点。

编辑: 作为对OP评论的回应,是的,看起来没有任何方法可以将FindFirst/FindNext配置为仅命中目录而不命中文件。但您可以使用此过滤器跳过检查文件上的日期: (SearchRec.Attr and SysUtils.faDirectory <> 0). 。这应该会加快一些速度。根本不要检查文件上的日期。不过,您可能仍然需要扫描所有内容,因为 Windows API 没有提供任何方式(据我所知)仅查询文件夹而不查询文件。

我为我的一个项目写了一个代码。这使用FindFirstChangeNotification和FindNextChangeNotification API函数。 这是代码(我删除了一些项目特定部分):

/// <author> Ali Keshavarz </author>
/// <date> 2010/07/23 </date>

unit uFolderWatcherThread;

interface

uses
  SysUtils, Windows, Classes, Generics.Collections;

type
  TOnThreadFolderChange = procedure(Sender: TObject; PrevModificationTime, CurrModificationTime: TDateTime) of object;
  TOnThreadError = procedure(Sender: TObject; const Msg: string; IsFatal: Boolean) of object;

  TFolderWatcherThread = class(TThread)
  private
    class var TerminationEvent : THandle;
  private
    FPath : string;
    FPrevModificationTime : TDateTime;
    FLatestModification : TDateTime;
    FOnFolderChange : TOnThreadFolderChange;
    FOnError : TOnThreadError;
    procedure DoOnFolderChange;
    procedure DoOnError(const ErrorMsg: string; IsFatal: Boolean);
    procedure HandleException(E: Exception);
  protected
    procedure Execute; override;

  public
    constructor Create(const FolderPath: string;
                       OnFolderChangeHandler: TOnThreadFolderChange;
                       OnErrorHandler: TOnThreadError);
    destructor Destroy; override;
    class procedure PulseTerminationEvent;
    property Path: string read FPath;
    property OnFolderChange: TOnThreadFolderChange read FOnFolderChange write FOnFolderChange;
    property OnError: TOnThreadError read FOnError write FOnError;
  end;

  /// <summary>
  /// Provides a list container for TFolderWatcherThread instances.
  /// TFolderWatcherThreadList can own the objects, and terminate removed items
  ///  automatically. It also uses TFolderWatcherThread.TerminationEvent to unblock
  ///  waiting items if the thread is terminated but blocked by waiting on the
  ///  folder changes.
  /// </summary>
  TFolderWatcherThreadList = class(TObjectList<TFolderWatcherThread>)
  protected
    procedure Notify(const Value: TFolderWatcherThread; Action: TCollectionNotification); override;
  end;

implementation

{ TFolderWatcherThread }

constructor TFolderWatcherThread.Create(const FolderPath: string;
  OnFolderChangeHandler: TOnThreadFolderChange; OnErrorHandler: TOnThreadError);
begin
  inherited Create(True);
  FPath := FolderPath;
  FOnFolderChange := OnFolderChangeHandler;
  Start;
end;

destructor TFolderWatcherThread.Destroy;
begin
  inherited;
end;

procedure TFolderWatcherThread.DoOnFolderChange;
begin
  Queue(procedure
        begin
          if Assigned(FOnFolderChange) then
            FOnFolderChange(Self, FPrevModificationTime, FLatestModification);
        end);
end;

procedure TFolderWatcherThread.DoOnError(const ErrorMsg: string; IsFatal: Boolean);
begin
  Synchronize(procedure
              begin
                if Assigned(Self.FOnError) then
                  FOnError(Self,ErrorMsg,IsFatal);
              end);
end;

procedure TFolderWatcherThread.Execute;
var
  NotifierFielter : Cardinal;
  WaitResult : Cardinal;
  WaitHandles : array[0..1] of THandle;
begin
 try
    NotifierFielter := FILE_NOTIFY_CHANGE_DIR_NAME +
                       FILE_NOTIFY_CHANGE_LAST_WRITE +
                       FILE_NOTIFY_CHANGE_FILE_NAME +
                       FILE_NOTIFY_CHANGE_ATTRIBUTES +
                       FILE_NOTIFY_CHANGE_SIZE;
    WaitHandles[0] := FindFirstChangeNotification(PChar(FPath),True,NotifierFielter);
    if WaitHandles[0] = INVALID_HANDLE_VALUE then
      RaiseLastOSError;
    try
      WaitHandles[1] := TerminationEvent;
      while not Terminated do
      begin
        //If owner list has created an event, then wait for both handles;
        //otherwise, just wait for change notification handle.
        if WaitHandles[1] > 0 then
         //Wait for change notification in the folder, and event signaled by
         //TWatcherThreads (owner list).
          WaitResult := WaitForMultipleObjects(2,@WaitHandles,False,INFINITE)
        else
          //Wait just for change notification in the folder
          WaitResult := WaitForSingleObject(WaitHandles[0],INFINITE);

        case WaitResult of
          //If a change in the monitored folder occured
          WAIT_OBJECT_0 :
          begin
            // notifiy caller.
            FLatestModification := Now;
            DoOnFolderChange;
            FPrevModificationTime := FLatestModification;
          end;

          //If event handle is signaled, let the loop to iterate, and check
          //Terminated status.
          WAIT_OBJECT_0 + 1: Continue;
        end;
        //Continue folder change notification job
        if not FindNextChangeNotification(WaitHandles[0]) then
          RaiseLastOSError;
      end;
    finally
      FindCloseChangeNotification(WaitHandles[0]);
    end;  
  except
    on E: Exception do
      HandleException(E);
  end;
end;

procedure TFolderWatcherThread.HandleException(E: Exception);
begin
  if E is EExternal then
  begin
    DoOnError(E.Message,True);
    Terminate;
  end
  else
    DoOnError(E.Message,False);
end;

class procedure TFolderWatcherThread.PulseTerminationEvent;
begin
  /// All instances of TFolderChangeTracker which are waiting will be unblocked,
  ///  and blocked again immediately to check their Terminated property.
  ///  If an instance is terminated, then it will end its execution, and the rest
  ///  continue their work.
  PulseEvent(TerminationEvent);
end;


{ TFolderWatcherThreadList }

procedure TFolderWatcherThreadList.Notify(const Value: TFolderWatcherThread;
  Action: TCollectionNotification);
begin
  if OwnsObjects and (Action = cnRemoved) then
  begin
    /// If the thread is running, terminate it, before freeing it.
    Value.Terminate;
    /// Pulse global termination event to all TFolderWatcherThread instances.
    TFolderWatcherThread.PulseTerminationEvent;
    Value.WaitFor;
  end;

  inherited;
end;

end.
.

这提供了两个类;监视文件夹的线程类,以及检测到更改,它将返回当前更改时间和先前的更改时间通过onfolderchange事件。以及用于存储监视线程列表的列表类。当从列表中删除线程时,此列表会自动终止每个自己的线程。

我希望它可以帮助你。

你应该看看 http://help.delphi-jedi.org / item.php?ID= 172977 ,即准备好的解决方案。 如果您不想下载并安装整个JVCL(但是这是一件很棒的代码;))您可能希望在线查看文件源 - http://jvcl.svn.sourceforge.net/viewvc/jvcl/trunk/jvcl/run/jvchangenotify.pas?修订= 12481&amp;查看= markup

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top