How to determine programmatically which program caught my file

My program is trying to write some data to a text file. But sometimes this file can only be opened by some other program.

How to programmatically determine which program caught my file? I should know the convenient name of the program (here is my second question :)) that did this.

+4
source share
1 answer

You detect this with the IOException that you get when you try to open a file. This is a necessary evil in a multitasking operating system; there is no reliable way to implement the File.IsLocked () method. Windows does not have an API function. Because if such a function returns false, another process may interrupt your program and lock the file. When you return the processor, you will find that the file is locked anyway. This is called thread buildup.

So, open the file with, say, the FileStream constructor. Pass FileShare.ReadWrite if you want to read from a file written by another process. You must enable the sharing of ReadWrite, another process has already received write permission. Catch the IOException you may get, you will have to try later. Tell the user about this, she probably knows what to do to help you. Like closing another program.

Btw, Windows provides no way to find out which other process is locked by the file. There are utilities for this, for example the SysInterals Handle utility. He understands the undocumented internal structures of the kernel with a dynamic device driver. Nothing that you would like to decide on your own.

+3
source

Source: https://habr.com/ru/post/1345699/


All Articles