I have the ntdll.dll's NtCreateFile() function hooked to allow/deny the access of certain files. Unlike kernel32.dll's CreateFile() which easily gives you the full path to the file in question, ntdll.dll's NtCreateFile() function only gives you the handle to the file. I need to obtain the full path of the file from a file handle, to consequently allow/deny access. I've searched around and there doesn't seem to be a working C# solution.
This solution is in C++, and documented from Microsoft. I've tried to port it over to C# with not much success. Here is my attempt at the C# equivalent of the C++ version of "obtaining a filename from a file handle":
public string GetFileNameFromHandle(IntPtr FileHandle)
{
string fileName = String.Empty;
IntPtr fileMap = IntPtr.Zero, fileSizeHi = IntPtr.Zero;
UInt32 fileSizeLo = 0;
fileSizeLo = GetFileSize(FileHandle, fileSizeHi);
if (fileSizeLo == 0 && fileSizeHi == IntPtr.Zero)
{
// cannot map an 0 byte file
return String.Empty;
}
fileMap = CreateFileMapping(FileHandle, IntPtr.Zero, FileMapProtection.PageReadonly, 0, 1, null);
if (fileMap != IntPtr.Zero)
{
IntPtr pMem = MapViewOfFile(fileMap, FileMapAccess.FileMapRead, 0, 0, 1);
if (pMem != IntPtr.Zero)
{
StringBuilder fn = new StringBuilder(250);
GetMappedFileName(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle, pMem, fn, 250);
if (fileName.Length > 0)
{
UnmapViewOfFile(pMem);
CloseHandle(FileHandle);
return fn.ToString();
}
else
{
UnmapViewOfFile(pMem);
CloseHandle(FileHandle);
return String.Empty;
}
}
}
return String.Empty;
}
I have, of course, all the necessary DLLImports and user-defined types. When I use this function on handles, I get an empty string in return. It's also pretty hard to debug this, since this method is in a DLL that gets injected into a target process, not like something you can set a breakpoint at and enjoy Visual Studio's debugging system. I guess I could write a log file or some trace system, but I'm not that desperate yet. I just need a successful C# version of "get filename from file handle".
Any insight, code fixes, links?