Detect File Read in C#

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.

Example: I have the file C:\test.txt on my harddrive and am watching it using FileSystemWatcher. Another program (not under my control) goes to read that file; I would like to catch that event and, if possible, check what program is reading the file then modify the contents of the file accordingly.

8
задан Petey B 1 September 2010 в 19:55
поделиться

2 ответа

Небольшой фрагмент, который мне показался полезным для обнаружения блокировки другого процесса:

 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; 
        }
-2
ответ дан 5 December 2019 в 21:15
поделиться

Вы можете использовать FileInfo.LastAccessTime и FileInfo.Refresh() в цикле опроса.

http://msdn.microsoft.com/en-us/library/system.io.fileinfo_members.aspx

1
ответ дан 5 December 2019 в 21:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: