Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out who locked file on a network drive in C#

Tags:

c#

windows

A program is running on multiple machines that share a network drive. It can use

... = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);

to lock a file from writing. All the other instance then can only read it and display a warning, that the file is not writable.

How can I find out who (i.e. which machine) locked the file, to display that along the warning?

like image 448
Niklas Avatar asked Aug 15 '12 14:08

Niklas


2 Answers

The only way I have ever seen this achieved is for the program that opens the file to leave behind a marker file, (.lock) or similar. This .lock file can then obviously contain whatever you want (username, machine etc) and can be read separately.

This assumes you have control over the software which is reading it on the other PC.

like image 116
KingCronus Avatar answered Oct 26 '22 22:10

KingCronus


Here is a posting with C# source code for an example of how to look through the process list and check the files that are locked by each process.

How does one figure out what process locked a file using C#.

The next step would be to use this functionality within a service on each machine so that a process can send a query for a specific file name and then receive a response as to whether a process on that machine has it locked.

The data could include process name, user id, and other information available from the process list.

This approach is more work however what it does is provide a way to access the information without require applications locking the file to do something special.

On the other hand if the files you are interested in are within your control and you can determine the file access, this is probably overkill.

like image 41
Richard Chambers Avatar answered Oct 26 '22 22:10

Richard Chambers