How to close a file handle which came from a parent process C#

523 views Asked by At

I'm creating an application updater module at the moment and have encountered a problem with an open file handle.

The updater module is a separate program but is launched via the application which is being updated via Process.Start() when the user clicks the 'upgrade' option. One of the first things the updater does is close down the application which is being updated so that it can be reinstalled without any file access issues etc.

Everything is fine up until the point where I try to remove the install directory of the application which is being updated. I get an exception which says:-

The process cannot access the file because it is being used by another process.

I've followed things through using the SysInternals Process Explorer utility. The updater program is initially a child process of the application which is being updated, but once the application to be updated is killed off the updater program is then its own parent. The issue appears to be that the updater program has an open file handle for the install directory of the application which is being updated.

I can resolve the issue manually by closing the file handle in Process Explorer before the updater gets to the point of attempting to remove the install folder and then the exception does not get thrown. However I need some way to close this file handle in code or avoid the file handle being held by the updater program process in the first place.

I've tried using the WIN32 CreateProcess method to create the process without inheriting handles, but the file handle for the install folder is still held by the updater program.

Any advice would be much appreciated.

1

There are 1 answers

3
usr On BEST ANSWER

This is probably the current directory of the process. If you start notepad with your install directory as it's current directory the same handle will appear. When you then use a file open dialog in notepad to navigate to some other directory the handle disappears.

Use Environment.CurrentDirectory to change the directory or create the child with a better current directory.