Search code examples
c#.netfilestreamfile-lockinginter-process-communicat

Passing stream objects / file handles between two processes in .NET


I have a windows service and a desktop application running on the same machine. The app pre-processes some documents and transfers them to a folder where the service can take over. When the app is creating the new file for the service, it keeps a read-only lock on the file while writing. It them releases it so that the service can acquire a new read-only lock (FileStream).

I'd like the app to somehow hand-over this lock to the service without closing it. Is this possible in the managed runtime? If not, is there a way to P/Invoke this behaviour?

The reason this behaviour is desired is so that no other processes can modify or delete the file until both the app and service are done with it.


Solution

  • This is not possible in a managed-only way.

    Try to use a simpler approach, such as naming the file with a random name in a temp directory such that no other application will try to open it.

    If you insist on passing the handle, you must duplicate the handle into the service process and pass the numeric handle value of that process to the service process. Use OpenProcess, DuplicateHandle and CloseProcess for that.

    From http://msdn.microsoft.com/en-us/library/windows/desktop/ms724251(v=vs.85).aspx:

    The duplicate handle refers to the same object as the original handle. Therefore, any changes to the object are reflected through both handles. For example, if you duplicate a file handle, the current file position is always the same for both handles. For file handles to have different file positions, use the CreateFile function to create file handles that share access to the same file.