How to detect programmatically what program caught my file
My program tries to write some data to a text file. But someti开发者_如何学Gomes this file can be opened by some other program exclusively.
How to detect programmatically what program caught my file? I have to know user-friendly program name (here is my second question :)) that did it.
You detect it by the IOException you get when you try to open the file. This is a necessary evil on a multi-tasking operating system, there is no reliable way to implement a File.IsLocked() method. Windows doesn't have an API function for it. Because if such a function returns false, another process could interrupt your program and lock the file. When you get the cpu back, you'll find that the file is locked anyway. That's called a threading race.
So open the file with, say, the FileStream constructor. Pass FileShare.ReadWrite if you want to read from a file that's being written by another process. You have to allow ReadWrite sharing, the other process already gained the write access right. Catch the IOException you may get, you'll have to try again 'later'. Tell the user about it, she'll probably know what to do to help you. Like closing another program.
Btw, Windows does not provide any way to find out what other process has the file locked. There are utilities for that, like SysInterals' Handle utility. It grovels through undocumented internal kernel structures with a device driver that's dynamically installed. Nothing you'd want to tackle yourself.
精彩评论