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.
Небольшой фрагмент, который мне показался полезным для обнаружения блокировки другого процесса:
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;
}
Вы можете использовать FileInfo.LastAccessTime и FileInfo.Refresh() в цикле опроса.
http://msdn.microsoft.com/en-us/library/system.io.fileinfo_members.aspx