0

I've seen several answers about using Handle or Process Monitor, but I would like to be able to find out in my code (C#) which process is locking a file.

Ex. I open two files like test.xlsx and test_1.xlsx and I want to close the only process of text.xlsx, but right whatever I find that close only my last open excel file or both files. This only example, I have so many files of different types and I need to close from them only several.

I try to "Handle" but it needs administrative rights, and restart manager also not provide exact process id which I use from different examples.

Nikunj Satasiya
  • 831
  • 9
  • 25
Hiren Jasani
  • 258
  • 2
  • 13
  • 2
    ASP.NET and WinForms? Neither of these are even remotely related to _this question_. – ProgrammingLlama Jan 21 '20 at 07:49
  • check out this answer: https://stackoverflow.com/a/20623311/5462775 – Ali Ezzat Odeh Jan 21 '20 at 08:04
  • @AliEzzatOdeh I already check that solution with restart manager, but it's not working as I needed. – Hiren Jasani Jan 21 '20 at 08:17
  • A definitive answer may not be (directly) possible. An Excel Process (as you mentioned it) owns multiple Windows. These Windows belong to the same Process. To close one, you should inspect the Captions to find the file name. You understand where this is going. This is just one possible scenario: there's no specific *protocol* that will let you identify the *right* Process and *close* it (kill it?) to free the *right* handle. Maybe explain in more details why you *have so many files of different types and I need to close from them only several*. Is it an Interop marshaling problem? – Jimi Jan 21 '20 at 09:38
  • You could go deeper and force the release of a handle. There's some documentation around. There are also consequences if you don't get it right. This, of course, in relation to file handles. If you instead are using Interop to interact with Office files and you don't know how to release the COM objects you generated so the handles don't close correctly, that's a different story. – Jimi Jan 21 '20 at 09:44
  • @Jimi I provide the functionality to move files from one to another location, but before that, we provide to check files but after that when we try to move that file than its raise exception, it's not related to excel files. – Hiren Jasani Jan 21 '20 at 10:44
  • 1
    Then you catch the exception and re-schedule the operation, or check whether the file is in use with the Restart Manager technology: [How do I find out which process has a file open?](https://devblogs.microsoft.com/oldnewthing/?p=8283) (the link to a SO solution you already have it) then, well, re-schedule or do whatever your application is meant to do when a file is found locked (common scenario for any backup program). – Jimi Jan 21 '20 at 10:55

0 Answers0