Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

c# - Directory Modification Monitoring

I'm building a C# application that will monitor a specified directory for changes and additions and storing the information in a database.

I would like to avoid checking each individual file for modifications, but I'm not sure if I can completely trust the file access time.

What would be the best method to use for getting recently modified files in a directory?

It would check for modifications only when the user asks it to, it will not be a constantly running service.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the FileSystemWatcher object. Here is some code to do what you are looking for.

    // Declares the FileSystemWatcher object
    FileSystemWatcher watcher = new FileSystemWatcher(); 

    // We have to specify the path which has to monitor

     watcher.Path = @"\somefilepath";     

    // This property specifies which are the events to be monitored
     watcher.NotifyFilter = NotifyFilters.LastAccess |
       NotifyFilters.LastWrite | NotifyFilters.FileName | notifyFilters.DirectoryName; 
    watcher.Filter = "*.*"; // Only watch text files.

    // Add event handlers for specific change events...

    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.Created += new FileSystemEventHandler(OnChanged);
    watcher.Deleted += new FileSystemEventHandler(OnChanged);
    watcher.Renamed += new RenamedEventHandler(OnRenamed);
    // Begin watching.
    watcher.EnableRaisingEvents = true;


    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
    // Specify what is done when a file is changed, created, or deleted.
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
    // Specify what is done when a file is renamed.
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...