保存文件时是否引发一般Windows事件(FileSystemWatcher类除外)

时间:2019-04-23 14:29:59

标签: c# windows events save

我想创建一个程序来检查用户是否通过Windows保存对话框保存了文件,是否有我可以订阅的常规Windows事件?

1 个答案:

答案 0 :(得分:0)

Ok based on recommendation of the comments I used the FileSystemWatcher class and used to watch all my discs.

And it's working without any problems referring to performance or resource issues.

Here's a litte test programm I wrote:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileSystemWatcherTest {
    class Program {
        static List<FileSystemWatcher> fsWatchers = new List<FileSystemWatcher>();

        static void Main(string[] args) {
            foreach(DriveInfo dInfo in DriveInfo.GetDrives()) {
                InitializeWatcher(dInfo.Name);
                Console.WriteLine("Initialized watcher for disc '" + dInfo.Name + "'");
            }

            Console.WriteLine("\nPress 'q' to exit");
            while (Console.Read() != 'q') ;

            DisposeWatchers();
        }

        static void DisposeWatchers() {
            foreach(FileSystemWatcher fsWatcher in fsWatchers) {
                fsWatcher.Dispose();
            }
        }

        static void InitializeWatcher(string DiscPath) {
            try {
                FileSystemWatcher fsWatcherToAdd = new FileSystemWatcher(DiscPath);

                fsWatcherToAdd.NotifyFilter = NotifyFilters.LastAccess
                                     | NotifyFilters.LastWrite
                                     | NotifyFilters.FileName
                                     | NotifyFilters.DirectoryName;

                fsWatcherToAdd.Created += FsWatcher_Created;

                fsWatcherToAdd.IncludeSubdirectories = true;
                fsWatcherToAdd.EnableRaisingEvents = true;

                fsWatchers.Add(fsWatcherToAdd);
            } catch {
            }           
        }

        private static void FsWatcher_Created(object sender, FileSystemEventArgs e) {
            Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + e.Name + " created...");
        }
    }
}