Get username of user who has file open on network drive - Microsoft Office Style

二次信任 提交于 2019-12-10 07:39:16

问题


I would like to add user friendly file locking to a software running under Windows (Windows 7 mostly), written in C#. I already achieved the file locking part, by keeping the files in use "open" in the corresponding process. What I now still would like to add is recognition of the user who has a file currently open/locked.

The files being accessed lie on a mapped network drive, used by different users on different computers. When a file is locked and a second person tries to open the file, he should be confronted with a dialog, similar to the "File in use"-dialog from the Microsoft Office programs. There, also the name of the user, currently editing the file, is displayed.

I found solutions to find out the processes, which have a certain file open (used this one: How do I find out which process is locking a file using .NET?) and I'm also able to read the name of the user who created this process out of it. However, when opening a locked file on a network drive, the username yielded by doing it like this, is always my own one, instead of the one from the user locking the file.

Does anyone have an idea how one could achieve this? I mean Microsoft Office somehow can do this on my same PC with the same user permissions, too. I just'd like to know how...

Cheers!


回答1:


Office uses a very simple technique, I'll talk about it in .NET terms. Whenever an Office app opens a document file, using FileShare.None, it also creates a hidden "lock-file" with a name that's based on the document file (say, with ".lockfile" appended). And writes Environment.UserDomainName into that file. The file is created with FileOptions.DeleteOnClose and FileShare.Read and kept open as long as the document file is open.

It closes the lock-file when the document is closed again. Using FileOptions.DeleteOnClose ensures that the lock-file disappears even when the program bombs.

When opening the file produces a locking violation, it goes looking for the lock-file and reads the user name. Easy peasy, simple to implement yourself. But can of course only work if it is one particular app that opens the file.



来源:https://stackoverflow.com/questions/33805734/get-username-of-user-who-has-file-open-on-network-drive-microsoft-office-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!