4

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

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

我很高兴通过树递归。我要避免的是必须为每个文件夹中的每个文件执行 FindFirst/FindNext,以查看是否在(例如)最后一天进行了修改 - 如果我可以避免对没有修改日期戳的文件夹执行此操作在最后一天内,它将节省大量时间。

4

4 回答 4

3

检查FindFirstChangeNotificationFindNextChangeNotification功能另一个选项是使用TJvChangeNotifyJEDI 组件。

另外你可以检查这个链接

于 2010-07-22T22:07:26.543 回答
2

为此,我为我的一个项目编写了一个代码。这使用 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 事件返回当前的变化时间和之前的变化时间。还有一个用于存储监控线程列表的列表类。当线程从列表中删除时,此列表会自动终止每个自己的线程。

我希望它对你有帮助。

于 2010-07-23T15:12:13.070 回答
2

迄今为止发布的解决方案都是关于在通知发生时获取通知,并且它们会很好地为此目的工作。如果您想查看过去并查看上次更改的时间,而不是实时监控它,那么它会变得更加棘手。我认为除了递归搜索文件夹树并检查日期戳之外,没有办法做到这一点。

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

于 2010-07-22T22:29:13.133 回答
0

你应该看看http://help.delphi-jedi.org/item.php?Id=172977这是一个现成的解决方案。如果您不想下载和安装整个 JVCL(不过这是一段很棒的代码;))您可能希望在线查看文件源 - http://jvcl.svn.sourceforge.net/viewvc/jvcl/trunk /jvcl/run/JvChangeNotify.pas?revision=12481&view=markup

于 2010-07-22T22:08:39.240 回答