Какой процесс держит файл windows

Ever wondered which program has a particular file or directory open? Quite often, when trying to delete a folder, Windows reports this:

Folder In Use

Folder In Use

The action can't be completed because the folder or a file in it is open in another program

This error also happens with a file, when we tried to move a file, or delete those file. How we can find out which program or application is currently using it and preventing us to delete/move it? To get the process holding those folder or file, we can use these two utilities:

  1. Resource Monitor
  2. Process Explorer

Resource Monitor

For Windows 7 and above, you can use the built-in Resource Monitor.

Open Resource Monitor, which can be found

  • By searching for resmon.exe in the start menu, or
  • As a button on the Performance tab in your Task Manager

Resource Monitor from Task Manager

Resource Monitor from Task Manager’s Performance Tab

From CPU tab, use the search field in the Associated Handles section

Resource Monitor

Resource Monitor

When you’ve found the handle, you can identify the process by looking at the Image and/or PID column. You can then close the application if you are able to do that, or just right-click the row and you’ll get the option of killing the process (End Process) right there.

Process Explorer

Process Explorer shows you information about which handles and DLLs processes have opened or loaded.

  • Open Process Explorer (running as «administrator») by running procexp.exe or procexp64.exe.
  • Enter the keyboard shortcut Ctrl+F. Alternatively, click the “Find” menu and select “Find a Handle or DLL”.

procexp Find Handle

Process Explorer — Find Handle or DLL

  • Type in the name of the locked file or other file of interest in the Search dialog box, then click «Search». Partial names are usually sufficient.
  • A list will be generated. There may be a number of entries. Click one of the entry, it’ll «Refreshing handles».

procexp Search

Process Explorer — Search

Same as Resource Monitor, an individual handle in the list can be killed by selecting it and pressing the delete key (or Close Handle). However, please be careful when deleting handles, as system instabilities may occur. Rebooting your system maybe will free the locked file/folder.

procexp Close Handle

Process Explorer — Close Handle

Handle is a command line version of Process Explorer.

My Take

I prefer to use Resource Monitor compare to Process Explorer since Process Explorer is slower (especially during «Refreshing handles» process). If I can’t find the handle in Resource Monitor, then I use Process Explorer.

When you try to open, delete, move, rename or edit a file, the action fails because a process is using the file and thus Windows returns an error that reads “”File In Use – the action can’t be completed because the file is open in another program“.

In some cases, Windows may prompt the error and tell you the which program is using the file, but in other cases, it will just show “open in another program” which you will have to figure it out yourself.

Windows 11 File in Use This action can't be completed

This guide will show you several methods on how to find out which process is currently using a specific file in Windows 11, and how to unlock a file that is locked by a process.

Find which process is using a file in Windows 11

In Windows 11, you can quickly check which process is using a file without installing any third party software. You can do so using the Resource Monitor tool in Windows 11, or by using a command line in Windows PowerShell or Command Prompt.

Check which process is locking a file using Resource Monitor

Resource Monitor is a Windows built-in tool that allows you to monitor resource consumption such as CPU, memory, disk and network usage of active processes in Windows 11. There is also a section called Associated Handles which you can search for the process that is using and locking a file by entering the name of the locked file.

  1. First, open Resource Monitor by typing resmon in the Start and hit Enter.
    Open Resource Monitor via Windows 11 Start

  2. In the Resource Monitor window, go to the CPU tab.
  3. Next, click on Associated Handles to expand the section.
  4. In the search box next to Associated Handles, type the name of the file that is locked by a program, then hit Enter to search.
  5. The search result will return any process it finds to be locking the file.
    How to Know Which Process is Using a File in Windows 11

In the example above, I have a file named sample.pdf which was locked by Adobe Acrobat Reader. Thus, when I search for sample.pdf in the Associated Handles, it returned AcroRd32.exe as the search result, which is the process that was locking the sample.pdf file.

Once you know which process is locking the file, you can then terminate the process by either closing the program manually or by killing the task via Task Manager so that you can perform action on that particular file.

Tip: Alternatively, you can also open Resource Monitor through Task Manager (Ctrl + Shift + Esc) > Performance > Open Resource Monitor.

Open Resource Monitor Windows 11

Windows PowerShell / Command Prompt

To identify which process is using a file via Windows Terminal (PowerShell) or Command Prompt in Windows 11, we need to use a command-line utility called Handle which allows users to tell which process is locking a specific file.

However, Handle is not included in Windows by default. You will need to first download it from https://docs.microsoft.com/en-us/sysinternals/downloads/handle.

The file you will be downloading is a zip file that contains the handle.exe. Once downloaded, extract the zip file to anywhere you want.

To correctly use handle.exe as a command line to find which process is using a specific file, in the folder where you’ve unzipped the handle.exe, right-click in the folder and select “Open in Windows Terminal” to open Windows PowerShell in this directory.

Open Windows Terminal PowerShell Windows 11

In the PowerShell window, enter the following command.

.\handle.exe -a -u "path to the locked file"

For example, to find the process that is locking my sample.pdf, I need to enter the following command.

.\handle.exe -a -u "C:\Users\alvin\Desktop\sample.pdf"

Find which process is using a file in Windows 11

If you run Command Prompt instead, use the following command. Make sure the command prompt is opened in the folder where you’ve extracted the handle.exe. Otherwise you will have to enter the full path to the handle.exe instead of just handle.exe.

handle.exe -a -u "path to the locked file"

How to unlock a file locked by a process using Unlocker

If you don’t mind downloading and installing a third party software, we recommend Unlocker by IObit. Unlocker is a simple utility tool for Windows that is able to identify the process that is locking a file and unlock the file directly should you choose to.

How to unlock file locked by process Windows 11

To learn how to unlock a locked file in Windows 11 using Unlocker, read: How to Force Delete a File in Use by Another Program on Windows 11/10.

Иногда при попытке удалить, переименовать или переместить какой-то файл в Windows вы можете получить сообщение, что файл занят/заблокирован/используется) другим процессом. Чаще всего имя программы, которая держит файл открытым указывается прямо в окне сообщения File Explorer. Чтобы снять блокировку файла достаточно просто закрыть эту программу. Но бывает ситуации, когда какой-то файл и библиотека используется неизвестным или системным процессом. В этом случае снять блокировку с файла немного сложнее.

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

Сообщение о блокировке файла может выглядеть по-разному. Например в следующем примере указан тип файла и с каким приложением он ассоциирован:

File/Folder in Use. The action can’t be completed because the file is open in another program. Close the folder or file and try again.
Файл уже используется. Операция не может быть завершена, так как файл или папка открыта в другой программе. Закройте файл и повторите попытку.

Файл уже используется. Операция не может быть завершена, так как файл или папка открыта в другой программе. Закройте файл и повторите попытку.

В этом случае вы можете легко понять какое приложение заблокировало файл и закрыть его.

Однако иногда можно увидеть более интересное сообщение, о том, что файл заблокирован неизвестным или системным процессом Windows. Это может быть, как процесс самой ОС Windows, так и другие процессе, работающий с правами System, например, антивирус, агент резервного копирования, база данных mssql и т.д.):

The action can’t be completed because the file is open in SYSTEM.
Файл уже используется. Действие не может быть выполнено, так как этот файл открыт в System.

Попробуем разобраться, как понять какой программой, службой или системным процессом Windows занят файл, как разблокировать файл и можно ли разблокировать файл не закрывая родительский процесс.

Самый простой вариант разблокировать файл – завершить процесс, которые его заблокировал. Но это не всегда возможно, особенно на серверах.

Чаще всего для поиска процесса, который заблокировал файл рекомендуют использовать утилиту Unlocker. Лично я
Unlocker
не использую, т.к. она не позволяет получить подробную информацию о процессе или цепочке процессов, которые заблокировали файл. Также нельзя освободить конкретный файл, занятый процессом – приходится завершать приложение целиком.

Кроме того, это сторонняя утилита, при установке которой нужно быть внимательным, т.к. в процессе она предлагает установить пачку ненужные программы в нагрузку.

Когда процесс в Windows открывает файл, этому потоку ввода/вывода назначается файловый дескриптор (handler). Процесс и его дочерние процессы получают доступ к файлу по этому дескриптору. Через Window API вы можете послать сигнал файловой системе на освобождение данного дескриптора и снятие блокировки с файла.

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

Как разблокировать файл с помощью Process Explorer?

ProcessExplorer это бесплатная утилита из набора системных утилит Sysinternals, которую можно скачать на сайте Microsoft (https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer). Попробуем с помощью Process Explorer найти, какой процесс заблокировал определенный файл и освободить этот файл, сбросив файловый дескриптор процесса.

  1. ProcessExplorer не требует установки, просто скачайте распакуйте и запустите с правами администратора
    procexp.exe
    ;
  2. Выберите меню Find -> Find Handle or DLL (или нажмите
    Ctrl-F
    );

    proc explorer - поиск открытых файлов

  3. Укажите имя файла, который нужно разблокировать и нажмите Search;
  4. Выберите нужный файл. Процесс, который открыл файлы будет выделен в дереве процессов. Можно завершить этот процесс, щелкнув по нему правой кнопкой и выбрав Kill Process Tree. Но можно попробовать закрыть дескриптор файла, не завершая процесс целиком. Дескриптор файла, который вы искали, автоматически выделяется в нижней панели Process Explorer. Щелкните по дескриптору правой кнопкой и выберите Close handle. Подтвердите закрытие файла.
    process explorer найти и завершить дескриптор процесса

    Если у вас в Process Explorer не отображается нижняя панель со списком открытых дескрипторов процесса, включите пункт меню View -> Lower Pane View -> Handles

Итак, вы закрыли дескриптор файла, не завершая родительский процесс. Теперь вы можете спокойно удалить или переименовать файл.

Сброс дескриптора файла с помощью утилиты Handle

Handle – это еще одна утилита командной строки из комплекта инструментов Sysinternals (доступна для скачивания на сайте Microsoft (https://docs.microsoft.com/en-us/sysinternals/downloads/handle. Она позволяет найти процесс, который заблокировал ваш файл и снять блокировку, освободив дескриптор.

  1. Скачайте и распакуйте архив с утилитой Handle;
  2. Запустите командную строку с правами администратора и выполните команду:
    handle64.exe > listproc.txt

    утилита Handle.exe

     Данная команда сохранит список открытых дескрипторов в файл. Можно вывести дескрипторы для каталога, в котором находится файл, который вы хотите изменить:
    Handle64.exe -a C:\Some\Path
    или конкретного процесса:
    handle64.exe -p winword.exe

  3. Откройте файл listproc.txt в любом текстовом редакторе и найдите строку, в которой указано имя заблокированного файла. Скопируйте ID дескриптора файла (значение в hex формате). Затем поднимитесь немного выше к разделу, в котором указан процесс, являющийся владельцем данного дескриптора и запишите его ID. Для процесса запущенного от имени системы скорее всего будет PID 4.
    список открытых дескрипторов файлов в windows

    Для некоторых системных процессов handle.exe вернет следующий текст:
    wininit.exe pid: 732 \<unable to open process>
    . Это означает, что вы не может получить информацию об этих системных процессах (даже с правами администратора). Для получения дескрипторов файлов, открытых такими процессами, запустите командную строку с правами System и попробуйте получить список дескрипторов еще раз.

  4. Теперь вернитесь в командную строку и сбросьте дескриптор файла по полученным HandleID и ProcessID. Формат команды следующий:
    handl64e.exe -c HandleID -p ProcessID
    Например:
    handl64e.exe -c 18C -p 18800

    handl64e - закрыть дескриптор открытого файла

  5. Утилита запросит подтвердить закрытие файла для указанного процесса. Подтвердите, нажав y -> enter

Если система отреагирует на закрытие файла корректно, вы разблокируете ваш файл без необходимости завершать процесс или перезагружать сервер/компьютер.

Я просматривал рабочий календарь, когда почтовая программа Outlook 2010 внезапно сообщила об ошибке и закрылась. После перезапуска она не смогла открыть OST-файл, и сегодня я расскажу, как решил эту проблему за три минуты.

При запуске программа выдавала такую ошибку:

Как определить программу, использующую файл

На работе у меня ОС и программы с английским интерфейсом, поэтому я приведу эквивалентный текст ошибки из русской версии Office.

Выполнен выход из Microsoft Outlook без правильного закрытия файла данных Outlook. Необходимо перезапустить Microsoft Outlook. Если ошибка повторится, обратитесь в службу поддержки.

Сообщение не блистало информативностью, а запуск почтового клиента в безопасном режиме, удерживая нажатой клавишу Ctrl, ничего не менял.

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

Как определить программу, использующую файл

Суть сообщения сводилась к тому, что OST-файл занят каким-то другим приложением, что и являлось препятствием для Outlook. Вы уже догадались, какую утилиту я запустил дальше?

В Process Explorer я нажал Ctrl + F и ввел в поиск .ost. В результатах немедленно отобразился «захватчик». Щелкнув по нему, я перешел в нижнюю панель Process Explorer и выбрал в контекстном меню команду Close Handle.

Как определить программу, использующую файл

Увеличить рисунок

Это решило проблему! Почтовая программа запустилась нормально, и я вернулся к работе.

Что делать, если веб-камера используется другим приложением

В комментариях читатель Игорь задал вопрос, можно ли использовать Process Explorer, чтобы определить, какое приложение использует веб-камеру. Да, процесс аналогичный, но искать нужно:

#vid

Я в курсе, что существует Unlocker, но его надо было еще скачать, а утилита Process Explorer находилась под рукой. К тому же, мораль записи не только в этих двух программах. Ведь прежде чем применять их, нужно было выйти на причину проблемы.

Upd. 11-Мар-13. Хотелось бы дополнить заметку моментами, всплывшими в ее обсуждении:

  • Если ничего нет под рукой, можно попытаться переименовать файл. Проводник может подсказать программу, использующую его.
  • В Windows 7 и выше можно воспользоваться встроенной программой «Монитор ресурсов» (resmon), где на вкладке CPU есть поиск дескрипторов.
  • Утилита NoVirus Thanks FileGovernor (описание)
  • Утилита NirSoft OpenFilesView (работает с ограничениями на х64).

А вам приходилось использовать Unlocker или Process Explorer в подобных ситуациях? Напишите в комментариях, какую из утилит вы применяли и в чем была проблема!

When a file or directory is in use by a process (application), you will not be able to delete or modify the file / directory.
Unfortunately it’s not always obvious which process is using the file.
Luckily, there is an easy way to find out without the need of 3rd party tools, which is what we’ll look at in this post.

If you prefer videos, you can see the same content in this video.

Error message

If you attempt to use File Explorer to delete a file that is in use by another process, you will get an error message similar to:

File In Use

The action can’t be completed because the file is open in [process name]

Close the file and try again.

File-in-use delete error message screenshot

If you attempt to delete the file in a different application, the wording of the error message may be different.

Similarly, if you attempt to modify a file that is in use by another process, you’ll likely get an error about not being able to write to the file because it’s in use or locked by another process.
Same thing if you try and rename or delete a directory that is in use by another process.
The exact wording of the error message will vary depending on the application being used to update / delete the file / directory.

Reproduce the above error message

To reproduce the above error, I used the following PowerShell script and then attempted to delete the file in File Explorer:

[string] $tempFilePath = "C:\Temp\FileLock\Temp.txt"
$tempFile = [System.IO.File]::Open($tempFilePath, [System.IO.FileMode]::OpenOrCreate)
# $tempFile.Dispose() # Close file when done reading/writing

Normally you would close the file using the Dispose method when done reading / writing, but I commented that out so the file lock would remain in place.

Finding which process is using the file / directory

Windows has a built-in way to see which processes are actively using a file or directory, using the Resource Monitor.

To open the Resource Monitor, you can simply hit the Windows Key and search for it.
It can also be found in the Task Manager’s Performance tab.

Task Manager Resource Monitor screenshot

Simply open the Resource Monitor, go to the CPU tab, and enter the file or directory path you want to check into the Search Handles box, making sure to not include quotes around the path.

Resource Monitor enter path screenshot

If a process has a handle to the file or directory, you should see results:

Resource Monitor process found screenshot

]

Note that it shows you the PID (Process ID) of the process that has the handle to the file or directory.
This is important because you may have several processes with the same name in Task Manager, so you can use the PID to identify which process is using the file or directory.

From there you can use the Task Manager to find out more about the process, or simply right-click the process in the Resource Monitor window and select End Process to kill the process and release the lock on the file / directory.

Once that is done you should be able to modify or delete the file or directory.

Happy process hunting :)

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Host файл windows 10 редактирование
  • Как удалить любую папку в windows 10 программа
  • Windows server enable ntp server
  • Microsoft security essentials windows server 2008 r2
  • Браузер сафари для windows отзывы