Пример #1
0
        public static bool GetFileNameFromHandle(IntPtr handle, out string fileName)
        {
            int[] length = { 0x2000 }; // 512 bytes

            using (SmartPtr sptr = new SmartPtr())
            {
                sptr.Allocate(length[0]);
                HandleFlag flag;
                if (!NativeMethods.GetHandleInformation(handle, out flag))
                {
                    fileName = null;
                    return(false);
                }
                if (flag != HandleFlag.None)
                {
                    fileName = null;
                    return(false);
                }
                NtStatus    ret         = default(NtStatus);
                ThreadStart threadStart = delegate
                {
                    ret = NativeMethods.NtQueryObject(handle, ObjectInformationClass.ObjectNameInformation,
                                                      sptr.Pointer, length[0], out length[0]);
                };
                Thread thread = new Thread(threadStart);
                thread.Start();
                bool result = thread.Join(100);
                if (!result)
                {
                    fileName = null;
                    return(false);
                }
                if (ret == NtStatus.BufferOverflow)
                {
                    sptr.ReAllocate(length[0]);
                    ret = NativeMethods.NtQueryObject(handle, ObjectInformationClass.ObjectNameInformation, sptr.Pointer,
                                                      length[0], out length[0]);
                }

                if (ret == NtStatus.Success)
                {
                    ObjectNameInformation oti =
                        (ObjectNameInformation)Marshal.PtrToStructure(sptr.Pointer, typeof(ObjectNameInformation));
                    UnicodeString unicodeName = oti.Name;
                    fileName = unicodeName.GetValue();
                    return(fileName.Length != 0);
                }
            }
            fileName = string.Empty;

            return(false);
        }