views:

18

answers:

1

Say you get a file handle from some outside DLL and instantiate a FileStream with it. It works just fine for reading and writing.

Then you want the path and name of that handle and try to access the Name property of your FileStream object, and it returns 'unknown'.

This is true for the constructors which takes file handles:

public FileStream(IntPtr handle, ...
public FileStream(SafeFileHandle handle, ...

I know the short answer, because it's not implemented. The private field _fileName of FileStream is never assigned in those constructors.

Seems the API to get the name from a handle involves more than one line of code, but I still think they could have bothered to include this.

So the real questions is: Why haven't they? Or did they just forget?

+1  A: 

There is no documented way to obtain the file name associated with a file handle. The example you linked can only work for memory mapped files, it relies on the GetMappedFileName() API function. No such API exists for regular file handles.

It is in fact possible, the SysInternals' Handle utility does it. The reason it isn't documented is that the structure of the kernel handle table is highly variable, it has changed for every Windows version. And, most of all, because it would allow extremely unsafe operations on a file handle, the kind that destroys file system integrity. People will use it to close a file handle owned by another process to get rid of a file locking problem.

You can probably find out how to do it by googling NtQuerySystemInformation. Make daily backups of your hard drive if you contemplate using it.

Hans Passant
@nubugz, Thanks for the explanation :) The code I linked to should work on all files, as it creates a mmf on the handle, grab the view and then uses the GetMappedFileName call on the view to get the filename/path. Very much a work around, and seemingly unnecessary operations for something which from the outside looks like it should be a simple OS call. Weird it's only implemented in regards to mmf's. But then again, we might not need the options to map from handle to name that often :)
Mikael Svenson
Hmm, on second thought, you're right. Iffy with a handle to a file in a shared folder on a remote server though. And the access rights matter. Anyhoo, nothing the .NET team would ever contemplate doing.
Hans Passant
I doubt they will either. Maybe we'll see an OS call sometime besides the mmf one. And I agree that a handle to a remote file seems a bit iffy. The mmf call will also have issues if the file isn't opened in a shared state since it won't get access to it.
Mikael Svenson