Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a file is open

Tags:

c#

file-io

Is there any way to determine if a file is open by anything include applications that do not lock the file (like notepad).

I need to detect when a given file myfile.txt is no longer open in any application including notepad - so i cannot use File.Open(...) with exclusive access to test since the file has no lock on it.

like image 947
schmoopy Avatar asked Jul 02 '10 02:07

schmoopy


People also ask

How can I tell if a file has been opened?

3. View recently opened files from other users on the same computer by clicking inside the File Explorer location bar and replacing the current user's name with a different user. Alternately, type “C:\Users\Username\Recent” into the location bar in (omitting quotes) and press “Enter.”

How do you check if a file is open in Windows?

System Tools > Shared Folders > Open Files This pane will display a list of all open files being accessed on that server in a Windows Server environment. Inside, you'll see the directory path of the file being accessed, the user's username, the file's status, and the number of locks on the file.

How do you check if a file is open or not in Linux?

The command lsof -t filename shows the IDs of all processes that have the particular file opened. lsof -t filename | wc -w gives you the number of processes currently accessing the file.


1 Answers

No. When Notepad has opened a file, it has read the entire file in and then closed it. So there is no trace in the OS that links Notepad's private memory with the file on disk.

Opening the file exclusively will not work, because Notepad does not have the file open. Searching Notepad's handle table will not work, because Notepad does not have the file open.

The only way to detect this is to write an unmanaged DLL that is injected into every process to scan their virtual memory, searching for the exact file contents. Not recommended.

like image 84
Stephen Cleary Avatar answered Sep 21 '22 07:09

Stephen Cleary