Detect File Read in C#

前端 未结 6 882
眼角桃花
眼角桃花 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 23:09

    A little snippet that I found useful for detecting when another process has a lock:

     static bool IsFileUsedbyAnotherProcess(string filename) 
            { 
                try 
                { 
                    using(var file = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                    }
                } 
                catch (System.IO.IOException exp) 
                { 
                    return true; 
                } 
                return false; 
            }
    

提交回复
热议问题