开发者

How come the Name property is <Unknown> on a FileStream which uses handle constructors?

开发者 https://www.devze.com 2022-12-26 02:57 出处:网络
Say you get a file handle from some outside DLL and instantiate a FileStream with it. It works just fine for reading and writing.

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消