Detect File Read in C#

前端 未结 6 879
眼角桃花
眼角桃花 2020-12-03 22:22

I\'m using FileSystemWatcher to check when a file is modified or deleted, but I\'m wondering if there is any way to check when a file is read by another application.

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 22:59

    The easiest way I can think of to do this would be with a timer (System.Threading.Timer) whose callback checks and stores the last

    System.IO.File.GetLastAccessTime(path)
    

    Something like (maybe with a bit more locking...)

    public class FileAccessWatcher
    {
    
    public Dictionary _trackedFiles = new Dictionary();
    
    private Timer _timer;
    
    public event EventHandler> FileAccessed = delegate { };
    
    public FileAccessWatcher()
    {
        _timer = new Timer(OnTimerTick, null, 500, Timeout.Infinite);
    }
    
    public void Watch(string path)
    {
        _trackedFiles[path] = File.GetLastAccessTime(path);
    }
    
    public void OnTimerTick(object state)
    {
        foreach (var pair in _trackedFiles.ToList())
        {
            var accessed = File.GetLastAccessTime(pair.Key);
            if (pair.Value != accessed)
            {
                _trackedFiles[pair.Key] = accessed;
                FileAccessed(this, new EventArgs(pair.Key));
            }
        }
    
        _timer.Change(500, Timeout.Infinite);
    }
    }
    

提交回复
热议问题