File handle windows detect

Handle v4.22

By Mark Russinovich

Published: June 14, 2019

Download Handle (887 KB)

Introduction

Ever wondered which program has a particular file or directory open? Now you can find out. Handle is a utility that displays information about open handles for any process in the system. You can use it to see the programs that have a file open, or to see the object types and names of all the handles of a program.

You can also get a GUI-based version of this program, Process Explorer, here at Sysinternals.

Installation

You run Handle by typing «handle». You must have administrative privilege to run Handle.

Usage

Handle is targeted at searching for open file references, so if you do not specify any command-line parameters it will list the values of all the handles in the system that refer to open files and the names of the files. It also takes several parameters that modify this behavior.

usage: handle [[-a] [-u] | [-c [-l] [-y]] | [-s]] [-p

Parameter Description
-a Dump information about all types of handles, not just those that refer to files. Other types include ports, Registry keys, synchronization primitives, threads, and processes.
-c Closes the specified handle (interpreted as a hexadecimal number). You must specify the process by its PID.
WARNING: Closing handles can cause application or system instability.
-l Dump the sizes of pagefile-backed sections.
-y Don’t prompt for close handle confirmation.
-s Print count of each type of handle open.
-u Show the owning user name when searching for handles.
-p Instead of examining all the handles in the system, this parameter narrows Handle’s scan to those processes that begin with the name process. Thus:
handle -p exp
would dump the open files for all processes that start with «exp», which would include Explorer.
name This parameter is present so that you can direct Handle to search for references to an object with a particular name.
For example, if you wanted to know which process (if any) has «c:\windows\system32» open you could type:
handle windows\system
The name match is case-insensitive and the fragment specified can be anywhere in the paths you are interested in.

Handle Output

When not in search mode (enabled by specifying a name fragment as a parameter), Handle divides its output into sections for each process it is printing handle information for. Dashed lines are used as a separator, immediately below which you will see the process name and its process id (PID). Beneath the process name are listed handle values (in hexadecimal), the type of object the handle is associated with, and the name of the object if it has one.

When in search mode, Handle prints the process names and id’s are listed on the left side and the names of the objects that had a match are on the right.

More Information

You can find more information on the Object Manager in Windows Internals, 4th Edition or by browsing the Object Manager name-space with WinObj.

Download Handle (887 KB)

Fix: Invalid File Handle on Windows 10

When you are trying to delete a file or folder on your system, you might come across the error message ‘Invalid file handle’. This error message occurs when the name of the folder or the file that you are trying to delete is a reserved name. The Windows operating system doesn’t deal with certain names/nicks due to which the File Explorer prevents you from giving your folder or file a reserved name. However, in case you get the file from your smartphone or another operating system like Linux, you will be prompted the said error message upon trying to delete it.

Invalid File Handle

Microsoft Naming Conventions

The Microsoft Naming Conventions provide that files or folders on your system should not be named CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. This is because these names are reserved names in the Windows operating system, meaning they are used for a specific purpose by the Windows operating system and should not be used anywhere else. You should also avoid following the above names immediately by an extension, for example, NUL.txt. In case you want some more details, you can refer to this article on Microsoft’s website.

What causes the ‘Invalid File Handle’ Error Message on Windows 10?

Well, the reason for the emergence of the said error is quite clear after giving the Naming Conventions provided by Microsoft a read.

  • The Name of the File/Folder is a Reserved Name: The error message occurs appears when the file you are trying to delete is given a reserved name. Using reserved names is prohibited by Microsoft and should not be trifled with.

Now that you are aware of the Microsoft Naming Conventions and the cause of the error message, you can overcome it by following the solution given down below.

Deleting the File or Folder

The files that are given a reserved name can be rendered useless because you can’t use them neither are you able to delete them using the standard procedure. To delete the file or folder, you will need to rely on some command prompt commands.

If you are facing the error message while deleting a directory, you can do so by following the steps given down below:

  1. Press Windows Key + X and select Command Prompt (Admin) from the list to open an elevated command prompt.
  2. Once the elevated command prompt opens up, type in the following command: Deleting a Folder with a Reserved Name
  3. In the above command, replace the path accordingly, however, make sure you do not remove the ‘\\.’ before the path. Another example would be:

The parameter /S is used to tell the rd command to remove all the sub-directories found in the specified directory while the /Q parameter is used to tell the command to remove contents of the specified directory silently (you won’t be given any prompts). Moreover, \\. is used to refer to the current system.

In case you are trying to delete a file, do the following:

  1. Open an elevated command prompt as shown above.
  2. Type in the following command and then hit Enter: Deleting a File with a Reserved Name
  3. To delete a file, you will just have to specify the extension of the file and use the command del instead of rd.

That’s it, you have probably deleted the file/folder from your system.

Свойства файла по его handle

Изменить стиль окна, зная его handle?
Можно ли с помощью Winapi функций изменить стиль окна, зная handle этого окна? например послав.

Как выбрать окно, если его handle не совпадает с handle процесса?
Добрый день! Задача на первый взгляд довольно простая: выбрать окно программы, переместить его в.

Нужно узнать имя и путь исполняемого файла, имея handle его окна
Нужно узнать имя и путь исполняемого файла, имея handle его окна. Когда используешь handle.

Как извлечь из wav-файла его свойства (частота, количество каналов)
Как извлечь из waw-файла его свойства(частота, количество канало і т.п)

Тематические курсы и обучение профессиям онлайн
Профессия Разработчик на C++ (Skillbox)
Архитектор ПО (Skillbox)
Профессия Тестировщик (Skillbox)

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Получить имя процесса по его handle
Всем привет, ищу статью по получению имени из хендла процесса. Кому не трудно, киньте пример или.

Как удалить объект, по его Handle
Как, зная Хендл объекта чужого приложения, удалить его?

Скрин чужого окна по его HANDLE
Прошу помощи\совета что то я никак не могу получить скрин окна по HANDLE ниже приведен код, он.

Получить информацию об окне, зная его handle
Подскажите, как зная хендл окна получить о нем информацию(есть ли в этом окне кнопки, сколько, их.

Getting executable file name from handle in Windows x64

I have a c# application that is compiled as x86 so it runs as a 32bit application on Windows 7 x64. While the application is running, I need to detect the executable name of the active window. On Winodws XP the following code worked fine (getting the process filename from the active window handle). On x64 it reports the name of only the 32bit processes (returning garbage for the others, probably because I’m not checking the data returned). I’m passing the handle of the active window that I got with the GetForegroundWindow API.

Can I get that piece of information form a 32bit process in a 64bit environment? Thanks. Andrea

2 Answers 2

FYI, there’s an API GetWindowModuleFileName that does all you want in a single call. I haven’t checked if it works any better in your scenario though.

Since there’s no error checking: have you stepped through the code and verified that the various API calls before GetModuleFileNameEx return sensible information? Also, you should define some symbolic constats instead of hardcoding the 1040 access specifier.

Have you tried using System.Diagnostics.Process.GetProcessById() ? It has a MainModule property from where you can grab FileName . Worth a shot, though.

Some cursory googling indicates you might be running your head into x64 vs. WoW64 walls, though. One of those more useful search results was this — summary: check out QueryFullProcessImageName.

Apparently WMI can bridge the WoW64 gap, allowing you to do SELECT ExecutablePath FROM Win32_Process WHERE ProcessID = %ProcessID% . In my experience WMI is somewhat heavy, so it would be a last resort.

How to get the name of a file from a file handle in Windows using C?

I’m trying to retrieve a file name from a given file handle.

I’ve seen that GetFileInformationByHandle could be useful, but the structure it returns does not contain any file name information (http://msdn.microsoft.com/en-us/library/aa363788%28v=VS.85%29.aspx).

How can I do this?

I’ve tried installing the Windows FileID APIs to get GetFileInformationByHandleEx working on Windows XP. But when including fileextd.h I get the following errors

From the following code:

5 Answers 5

Hi if you need file name from handle you can read this ms article http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx or use this GetFileInformationByHandleEx

There is a correct way to do this that works on Windows XP, on both files and directories; I’ve explained it in another post here.

For Vista and later take a look at GetFinalPathNameByHandle (like mehrdad wrote)

It is more convenient IMO and allows more customization than GetFileInformationByHandleEx, and it removes the hassle of allocating a custom size FILE_NAME_INFO struct.

Notice, it will prepend \\?\ to the returning name.

(I used C++ std::wstring to avoid C boilerplate for memory handling. Use malloc for your needs).

Where did you get the file handle from? If you’re sure it’s not a named pipe handle, you can use NtQueryObject to query the file name.

Not the answer you’re looking for? Browse other questions tagged c windows filehandle or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Читайте также:  Для чего нужен apache linux
Оцените статью