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

Unable to delete or move or perform any action on a file because it is locked by a process? Find out which process is locking a file in Windows 11/10 using various methods discussed in this article.

Many times, when we attempt an action (delete, rename, copy, etc.) on a file, we get a File in Use dialog box showing a prompt that “The action can’t be completed because the file is open in another program“. In some cases, it will show the process or program name that is using the file. But, a lot of times, it doesn’t.

Now, how to tell which process has a file open? If it is urgent, you need to identify the process locking a file and then end the process to modify the target file. In this guide, we will be discussing different methods to check the process that is holding a file in Windows 11/10.

How to tell which process is locking a file in Windows 10

Here are the different methods to identify the process that is locking a file in Windows 11/10:

  1. Check the process that is locking a file using Resource Monitor.
  2. Use SysInternals Process Explorer to identify the process that is locking a file.
  3. Find out through Command Prompt using the Handle tool.
  4. Use OpenedFilesView freeware to identify the process holding a file.

Let’s elaborate on these methods now.

1] Check the process that is locking a file using Resource Monitor

Using Resource Monitor, you can identify the process or service locking a file. It is an inbuilt utility in Windows 10 that helps you monitor CPU usage, memory, disk network, file handles, etc.

Open Run app by pressing Windows + R hotkey and then type resmon in it. Press the OK button and Resource Monitor will open up.

In the Resource Monitor window, go to the CPU tab and expand the Associated Handles option. Now, in the search box, type the name of the file that is showing locked by a process and press Enter button. It will show you a list of processes holding the target file.

You can right-click on the process and select the End Process option to end it. After the process ends, try performing the action you wanted to on the previously locked file.

2] Use SysInternals Process Explorer to identify the process that is locking a file

Another option to identify the process or service holding a file is SysInternals Process Explorer. It is an advanced utility to find out detailed information regarding running processes on your system. To identify the process holding a file through it, you can follow below steps:

Firstly, download and run SysInternals Process Explorer on your PC. Now, in the Process Explorer window, go to the File menu and click on the Find Handle or DLL option. Next, enter the file name in the Process Explorer Search dialog window and press the Search option. All the processes that are using the file you entered will show up in the results.

Right-click on the identified process in the Process tab and then close it.

Now, check with the file if it is still held or locked by a process or not.

Related: The process cannot access the file because it is being used by another process.

3] Find out through Command Prompt using Handle tool

Handle is a command-based utility to tell which process has a file open. It is basically a command-line version of the above discussed SysInternals Process Explorer. You can follow the below steps to check the process holding a file in command prompt using this tool:

Download Handle from microsoft.com and extract the ZIP folder. Now, open CMD in the extracted folder. In the Command Prompt, enter a command with the following syntax:

handle.exe -a -u <filename-with-path>

For example:

handle.exe -a -u "C:\Users\KOMAL\Documents\Sample Files\twc.pdf"

As you enter the command, it will display a list of processes holding the file with process ID and username.

I tried to check the same by entering just the filename without the full path, it worked. But, it may not work for all files. So, it is recommended to enter the location of the locked file.

After identifying the process, you can close it from Task Manager.

4] Use OpenedFilesView freeware to identify the process holding a file

OpenedFilesView is a portable application to view all your opened files and the processes holding them. You can download its ZIP folder, extract it, and then run its OpenedFilesView.exe file to launch its interface. It will then display all currently opened files with respective details including process name, process ID, process path, file permissions, target file path, etc.

Locate your target file and check which process is holding it. Also, you can use its Find option to quickly search for a locked file and the associated process. After finding the process, right-click on the file and close all the processes holding it.

TIP: You can also use File Locksmith PowerToy.

Hope this guide helps you identify the process of holding a file and then closing it.

Now read: Delete Locked Files, and fix File Is Locked error.

Файл занят другим процессом, заблокирован другим процессом или открыт в другой программе — простое решение

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

В этой простой инструкции новый простой способ узнать, какой именно процесс мешает действиям с файлом или папкой в Windows 11 и Windows 10, закрыть такую программу и выполнить требуемые изменений. На близкую тему может быть полезным: Как удалить файл, который не удаляется в Windows.

File Locksmith — новая функция Microsoft PowerToys для разблокировки файлов

Заблокированный другим процессом файл или папка — типичная ситуация, при этом Windows не всегда сообщает пользователю, о каком именно процессе идёт речь.

Процесс не может получить доступ к файлу, сообщения об ошибке

На сайте уже несколько раз обновлялся обзор полезной и бесплатной утилиты Microsoft PowerToys, содержащей набор инструментов для работы в системах Windows 10 и Windows 11. В начале ноября в ней появилась ещё одна возможность — File Locksmith, которая и поможет в рассматриваемой ситуации.

File Locksmith позволяет легко определить, какие процессы используют файл или папку (а точнее — её содержимое) и быстро закрыть эти процессы. Далее подробно о том, как именно работает функция:

  1. Установите Microsoft PowerToys, если ещё не установили. Проще всего это сделать из магазина приложений Microsoft Store используя поиск в магазине или ссылку https://aka.ms/getPowertoys, также есть другие способы загрузки: https://learn.microsoft.com/ru-ru/windows/powertoys/install
  2. После первого запуска приложения может потребоваться перезапуск PowerToys от имени администратора в главном окне приложения (в моем тесте функция File Locksmith не появилась в меню до выполнения перезапуска на одном из устройств). Перезапуск Microsoft Powertoys от имени администратора
  3. В параметрах Microsoft PowerToys убедитесь, что функция File Locksmith включена. Функция File Locksmith в Microsoft Powertoys
  4. Нажмите правой кнопкой мыши по файлу, который занят другим процессом и выберите пункт меню «Какие процессы используют этот файл?». В Windows 11 потребуется предварительно открыть классическое контекстное меню, нажав «Показать дополнительные параметры». Посмотреть какие процессы используют этот файл
  5. Откроется окно со списком процессов, использующих этот файл. Если процесс не отображается, выполните перезапуск окна с правами администратора, нажав по значку справа вверху. Процессы использующие файл
  6. Раскрыв свойства процесса, вы можете узнать его идентификатор (например, для завершения вручную), а также от имени какого пользователя он запущен. Информация о процессе в File Locksmith
  7. Действие по проверке использующих элемент процессов можно применять и к папке, в таком случае будет отображаться список всех процессов, использующих её содержимое, а раскрыв сведения можно получить информацию о том, какие именно файлы использует этот процесс. Какие процессы используют файлы в папке
  8. И, самое главное, прямо в окне File Locksmith можно завершить процесс. Однако будьте осторожны при завершении системных процессов Windows.

Надеюсь, новый инструмент будет полезен. Конечно, есть и другие возможности, например, многие используют Unlocker, но вариант с File Locksmith куда более безопасен для пользователя, на мой взгляд.

Категория:
Технические советы
– Автор:
Игорь (Администратор)
  • Как узнать, какие программы использует файл в Windows 7?
  • Как узнать, какие программы и DLL держат открытые маркеры (дескрипторы) на файл в Windows 7?

Иногда, при попытке удалить, переместить или переименовать файл, могут возникать различные окна с системными предупреждениями следующего вида: 

  • Доступ к файлу запрещен - Как узнать, какие процессы Windows используют файл?«Не удается удалить файл: отказано в доступе» / «Cannot delete file: Access is denied»
  • «Обнаружена проблема общего доступа» / «There has been a sharing violation»
  • «Исходный файл возможно используется» / «The source or destination file may be in use»
  • «Файл используется другой программой или пользователем» / «The file is in use by another program or user».
  • «Убедитесь, что диск не переполнен и не защищен от записи и что файл не используется в настоящее время» / «Make sure the disk is not full or write-protected and that the file is not currently in use»

Одним из лучших способов справиться с заблокированными файлами и каталогами — это воспользоваться бесплатной программой Process Explorer от Microsoft. Программа уже была описана в обзоре Лучшие бесплатные диспетчеры процессов, и вот как ее можно использовать для того, чтобы узнать какой процесс или какая DLL блокирует доступ к файлу. Вам потребуются права администратора.

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

Как узнать, какие программы использует файл в Windows 7?

В Windows 7 и выше, системное сообщение может содержать название программы, блокирующую доступ к файлу. В Windows XP, обычно, такой информации нет. В любом случае, есть простой способ, как можно найти программу:

process explorer - Как узнать, какие процессы Windows используют файл?

  1. Откройте Process Explorer от имени администратора
  2. На панели инструментов найдите значок в виде прицела (иконка выделена на рисунке выше)
  3. Перетащите иконку на заблокированный файл или каталог
  4. Программы, которые используют данный файл, будут подсвечены в общем списке процессов в главном окне Process Explorer

Как узнать, какие программы и DLL держат открытые маркеры (дескрипторы) на файл в Windows 7?

  1. Откройте Process Explorer от имени администратора
  2. Нажмите комбинацию клавиш «Ctrl + F». Или выберите в меню «Поиск» пункт «Find a Handle or DLL»
  3. Откроется диалоговое окно поиска
  4. Введите имя заблокированного файла или часть его названия. Как правило, достаточно части имени
  5. Нажмите кнопку «Поиск»
  6. Откроется список со всеми программами и dll, которые используют данный файл. Вернее их открытые маркеры (дескрипторы) на файл
  7. Вы можете удалить все маркеры (дескрипторы) простым нажатие кнопки «Delete», чтобы разблокировать доступ к файлу. Тем не менее, обращаем ваше внимание на то, что при удалении дескрипторов, могут возникнуть проблемы. Например, если это сделать во время сохранения файла, то информация в файле может быть повреждена. Поэтому, если вы сомневаетесь, то можете просто перезагрузить компьютер. Часто, этого вполне достаточно, чтобы разблокировать доступ к файлу.

Process Explorer можно скачать здесь.

Примечание: Как альтернативу, вы так же можете программы из обзора Лучшие бесплатные утилиты для удаления блокированных файлов. Несмотря на их название, они так же позволяют копировать и перемещать файлы. А так же позволяют обойти ряд таких ограничений, как блокировка доступа к файлу при старте системы.

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

☕ Понравился обзор? Поделитесь с друзьями!

  • Как отключить историю поисковых запросов для аккаунтов Google?

    Как отключить историю поисковых запросов для аккаунтов Google?
    Технические советы

  • EMET мощный инструмент от Microsoft для обеспечения безопасности Windows

    EMET мощный инструмент от Microsoft для обеспечения безопасности Windows
    Технические советы

  • Где найти бесплатные иконки?

    Где найти бесплатные иконки?
    Технические советы

  • Как узнать какие программы подключены к Интернету (CurrPorts)?

    Как узнать какие программы подключены к Интернету (CurrPorts)?
    Технические советы

  • Как настроить автоматический запуск программ или скриптов при выключении Windows?

    Как настроить автоматический запуск программ или скриптов при выключении Windows?
    Технические советы

  • Программа Hwinfo характеристики компьютера и проверка состояния устройств в Windows

    Программа Hwinfo характеристики компьютера и проверка состояния устройств в Windows
    Технические советы

Добавить комментарий / отзыв

Наверное, каждому из пользователей Windows хотя бы раз приходилось иметь дело с так называемыми неудаляемыми файлами и папками. Как правило, причиной невозможности удалить, переместить или хотя бы переименовать такой объект является использование его каким-то процессом, причём необязательно чтобы этот процесс был системным. Это может быть антивирус, архиватор или какой-нибудь редактор.

Обычно в окне с ошибкой прямо указывается, что за процесс препятствует дальнейшим действиям с объектом, но бывает и так, что вместо этого сообщается, что файл или папка открыты в другой программе. Это понятно, но вот в какой именно?

Ошибка

Так вот, определить её очень просто. Во всех популярных версиях Windows (начиная с 7) есть такая встроенная утилита как «Монитор ресурсов», предназначающаяся для контроля использования программных и аппаратных ресурсов. В её поле зрения попадают все процессы, в том числе и зависшие. Она то как раз и подскажет, что именно держит файл или папку.

Нажмите сочетание клавиш Win + R и выполните в открывшемся окошке команду resmon.

Программа выполнить

Откроется окно монитора ресурсов. Переключитесь в нём на вкладку «ЦП» и введите в поле «Поиск дескрипторов» название объекта, при удалении, перемещении или переименовании которого возникла ошибка. Результаты отобразятся тут же, чуть ниже. В нашем примере удалению папки «Всякая всячина» препятствовал архиватор WinRAR, но в самом окне с описанием ошибки об этом ничего не говорилось.

Монитор ресурсов

Вот так всё просто. Кстати, если удерживающий процесс не является критическим, его можно завершить прямо из окна монитора ресурсов.

Завершение процесса

После этого проблемный файл, папка или другой объект легко смогут быть удалены обычным способом.

Загрузка…

One thing that annoys me no end about Windows is the old sharing violation error. Often you can’t identify what’s holding it open. Usually it’s just an editor or explorer just pointing to a relevant directory but sometimes I’ve had to resort to rebooting my machine.

Any suggestions on how to find the culprit?

Alan Fleming's user avatar

asked May 1, 2009 at 0:47

cletus's user avatar

6

I’ve had success with Sysinternals Process Explorer. With this, you can search to find what process(es) have a file open, and you can use it to close the handle(s) if you want. Of course, it is safer to close the whole process. Exercise caution and judgement.

To find a specific file, use the menu option Find->Find Handle or DLL... Type in part of the path to the file. The list of processes will appear below.

If you prefer command line, Sysinternals suite includes command line tool Handle, that lists open handles.

Examples

  • c:\Program Files\SysinternalsSuite>handle.exe |findstr /i "e:\" (finds all files opened from drive e:\«
  • c:\Program Files\SysinternalsSuite>handle.exe |findstr /i "file-or-path-in-question"

bjoster's user avatar

bjoster

4,8125 gold badges25 silver badges33 bronze badges

answered May 1, 2009 at 1:03

Eddie's user avatar

EddieEddie

11.4k8 gold badges37 silver badges48 bronze badges

18

You can use the Resource Monitor for this which comes built-in with Windows 7, 8, and 10.

  1. Open Resource Monitor, which can be found
    • By searching for Resource Monitor or resmon.exe in the start menu, or
    • As a button on the Performance tab in your Task Manager
  2. Go to the CPU tab
  3. Use the search field in the Associated Handles section
    • See blue arrow in screen shot below

When you’ve found the handle, you can identify the process by looking at the Image and/or PID column.

You can then try to close the application as you normally would, or, if that’s not possible, just right-click the handle and kill the process directly from there. Easy peasy!

Resource Monitor screenshot

Copied from my original answer: https://superuser.com/a/643312/62

answered Sep 10, 2013 at 11:48

Svish's user avatar

SvishSvish

7,02715 gold badges38 silver badges45 bronze badges

13

Just be very careful with closing handles; it’s even more dangerous than you’d think, because of handle recycling — if you close the file handle, and the program opens something else, that original file handle you closed may be reused for that «something else.» And now guess what happens if the program continues, thinking it is working on the file (whose handle you closed), when in fact that file handle is now pointing to something else.

see Raymond Chen’s post on this topic

Suppose a search index service has a file open for indexing but has
gotten stuck temporarily and you want to delete the file, so you
(unwisely) force the handle closed. The search index service opens its
log file in order to record some information, and the handle to the
deleted file is recycled as the handle to the log file. The stuck
operation finally completes, and the search index service finally gets
around to closing that handle it had open, but it ends up unwittingly
closing the log file handle.

The search index service opens another
file, say a configuration file for writing so it can update some
persistent state. The handle for the log file gets recycled as the
handle for the configuration file. The search index service wants to
log some information, so it writes to its log file. Unfortunately, the
log file handle was closed and the handle reused for its configuration
file. The logged information goes into the configuration file,
corrupting it.

Meanwhile, another handle you forced closed was reused
as a mutex handle, which is used to help prevent data from being
corrupted. When the original file handle is closed, the mutex handle
is closed and the protections against data corruption are lost. The
longer the service runs, the more corrupted its indexes become.
Eventually, somebody notices the index is returning incorrect results.
And when you try to restart the service, it fails because its
configuration files have been corrupted.

You report the problem to the
company that makes the search index service and they determine that
the index has been corrupted, the log file has mysteriously stopped
logging, and the configuration file was overwritten with garbage. Some
poor technician is assigned the hopeless task of figuring out why the
service corrupts its indexes and configuration files, unaware that the
source of the corruption is that you forced a handle closed.

Community's user avatar

answered May 30, 2009 at 17:04

Mark Sowul's user avatar

Mark SowulMark Sowul

1,8391 gold badge11 silver badges14 bronze badges

10

If you are having enough privileges, try the openfiles command.

You might have to enable listing of localy opened files by running openfiles /local on and rebooting.

Paul's user avatar

Paul

3,0476 gold badges27 silver badges40 bronze badges

answered May 1, 2009 at 1:18

John Fouhy's user avatar

John FouhyJohn Fouhy

1,1417 silver badges4 bronze badges

7

I’ve used Handle with success to find such processes in the past.

answered May 1, 2009 at 0:52

Greg Hewgill's user avatar

Greg HewgillGreg Hewgill

6,8793 gold badges30 silver badges26 bronze badges

2

Just to clarify, this is more likely to be a result of misbehaving 3rd party apps not using the CreateFile API call correctly than it is to be anything in Windows itself. Perhaps it’s a consequence of the design of CreateFile, but done is done and we can’t go back.

Basically when opening a file in a Windows program you have the option to specify a flag that allows shared access. If you don’t specify the flag, the program takes exclusive access of the file.

Now, if Explorer seems to be the culprit here, it may be the case that that’s just on the surface, and that the true culprit is something that installs a shell extension that opens all files in a folder for it’s own purposes but is either too gung-ho in doing so, or that doesn’t clean up properly after itself. Symantec AV is something I’ve seen doing this before, and I wouldn’t be surprised if other AV programs were also to blame. Source control plug-ins may also be at fault.

So not really an answer, but just some advice to not always blame Windows for what may be a badly written 3rd party program (something that can also happen on any other OS which has implicit file locking, but any unix based OS has shared access by default).

Community's user avatar

answered Oct 12, 2009 at 14:27

Maximus Minimus's user avatar

Maximus MinimusMaximus Minimus

8,9872 gold badges23 silver badges36 bronze badges

2

On a remote server, when you’re checking on a network share, something as simple as the Computer Management console can display this information and close the file.

answered May 1, 2009 at 1:01

K. Brian Kelley's user avatar

1

Apropos Explorer holding a file open: «When this happens on a file you need to delete, you have the choice of forcing the handle closed, or rebooting.»

You can just end Explorer.

If this is a one-time thing (Explorer does not normally hold this file open) then I would guess logging off and logging back on will do the trick.

Otherwise, kill the desktop Explorer process and do what you want while it’s gone. First start a copy of cmd.exe (you need a UI to do your intended cleanup). Make sure there are no non-desktop Explorers running. Then kill the last Explorer with, e.g., Task Manager. Do what you want in the command prompt. Finally, run Explorer from the command prompt, and it will become the desktop.

I’d guess there may be some residual unpleasantness if some systray programs can’t deal with the shell restarting.

answered Jun 3, 2009 at 14:01

1

Who Lock Me works well and keeps people amused with the name!

yagmoth555's user avatar

yagmoth555

16.8k4 gold badges29 silver badges50 bronze badges

answered May 6, 2009 at 0:43

Generic Error's user avatar

Generic ErrorGeneric Error

5933 gold badges8 silver badges16 bronze badges

2

Files can be locked by local processes (unlocker is the tool to use) and by file access that comes in through shares.

There is a built-in function in Windows that shows you what files on the local computer are open/locked by remote computer (which has the file open through a file share):

* Select "Manage Computer" (Open "Computer Management")
* click "Shared Folders"
* choose "Open Files"

There you can even close the file forcefully.

answered Oct 12, 2009 at 12:53

Dirk Paessler's user avatar

Dirk PaesslerDirk Paessler

9141 gold badge7 silver badges15 bronze badges

With Process Hacker you can identify what processes are holding your files easily:

Find Handles or DLLs

answered Oct 12, 2016 at 23:07

Ivan Kochurkin's user avatar

Ivan KochurkinIvan Kochurkin

1831 gold badge1 silver badge6 bronze badges

There have new PowerToys available from Microsoft.

File Locksmith utility for Windows | Microsoft Learn
https://learn.microsoft.com/en-us/windows/powertoys/file-locksmith

After installing PowerToys, right-click on one or more selected files in File Explorer, and then select What’s using this file? from the menu.

answered Nov 21, 2022 at 6:54

Ivan Chau's user avatar

Ivan ChauIvan Chau

2711 silver badge12 bronze badges

The above upvoted answers cover situations where a program process is holding the file handle open, which (fortunately) is most of the time — however in some cases (as is occurring on this system at the moment), the system itself holds a file handle open.

You can identify this situation by following the instructions to find the file handle holding process with process explorer above, and noting that the process name is listed as ‘system’, or by following the the instructions using resource monitor and noting that no image is shown having a filehandle open on your file of interest (Although obviously something does as you can’t edit/delete etc the file).

If that happens, your option (so far as I’m aware) is to restart — or forget about doing anything with that file.

answered May 16, 2017 at 0:51

Blair's user avatar

BlairBlair

312 bronze badges

I got turned on to the Free Extended Task Manager a while ago by Jeremy Zawodny’s blog, and it’s great for tracking down further info on processes too. +1 for Process Explorer as above, too, especially for killing processes that the standard Task Manager won’t end.

Gerold Broser's user avatar

answered May 16, 2009 at 20:16

nedm's user avatar

nedmnedm

5,6405 gold badges32 silver badges52 bronze badges

You can also do it programmatically by leveraging on the NTDLL/KERNEL32 Windows API. E.g. have a look at the following code in Python:

import ctypes
from ctypes import wintypes

path = r"C:\temp\test.txt"

# -----------------------------------------------------------------------------
# generic strings and constants
# -----------------------------------------------------------------------------

ntdll = ctypes.WinDLL('ntdll')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

NTSTATUS = wintypes.LONG

INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
FILE_READ_ATTRIBUTES = 0x80
FILE_SHARE_READ = 1
OPEN_EXISTING = 3
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000

FILE_INFORMATION_CLASS = wintypes.ULONG
FileProcessIdsUsingFileInformation = 47

LPSECURITY_ATTRIBUTES = wintypes.LPVOID
ULONG_PTR = wintypes.WPARAM


# -----------------------------------------------------------------------------
# create handle on concerned file with dwDesiredAccess == FILE_READ_ATTRIBUTES
# -----------------------------------------------------------------------------

kernel32.CreateFileW.restype = wintypes.HANDLE
kernel32.CreateFileW.argtypes = (
    wintypes.LPCWSTR,      # In     lpFileName
    wintypes.DWORD,        # In     dwDesiredAccess
    wintypes.DWORD,        # In     dwShareMode
    LPSECURITY_ATTRIBUTES,  # In_opt lpSecurityAttributes
    wintypes.DWORD,        # In     dwCreationDisposition
    wintypes.DWORD,        # In     dwFlagsAndAttributes
    wintypes.HANDLE)       # In_opt hTemplateFile
hFile = kernel32.CreateFileW(
    path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, None, OPEN_EXISTING,
    FILE_FLAG_BACKUP_SEMANTICS, None)
if hFile == INVALID_HANDLE_VALUE:
    raise ctypes.WinError(ctypes.get_last_error())


# -----------------------------------------------------------------------------
# prepare data types for system call
# -----------------------------------------------------------------------------

class IO_STATUS_BLOCK(ctypes.Structure):
    class _STATUS(ctypes.Union):
        _fields_ = (('Status', NTSTATUS),
                    ('Pointer', wintypes.LPVOID))
    _anonymous_ = '_Status',
    _fields_ = (('_Status', _STATUS),
                ('Information', ULONG_PTR))


iosb = IO_STATUS_BLOCK()


class FILE_PROCESS_IDS_USING_FILE_INFORMATION(ctypes.Structure):
    _fields_ = (('NumberOfProcessIdsInList', wintypes.LARGE_INTEGER),
                ('ProcessIdList', wintypes.LARGE_INTEGER * 64))


info = FILE_PROCESS_IDS_USING_FILE_INFORMATION()

PIO_STATUS_BLOCK = ctypes.POINTER(IO_STATUS_BLOCK)
ntdll.NtQueryInformationFile.restype = NTSTATUS
ntdll.NtQueryInformationFile.argtypes = (
    wintypes.HANDLE,        # In  FileHandle
    PIO_STATUS_BLOCK,       # Out IoStatusBlock
    wintypes.LPVOID,        # Out FileInformation
    wintypes.ULONG,         # In  Length
    FILE_INFORMATION_CLASS)  # In  FileInformationClass

# -----------------------------------------------------------------------------
# system call to retrieve list of PIDs currently using the file
# -----------------------------------------------------------------------------
status = ntdll.NtQueryInformationFile(hFile, ctypes.byref(iosb),
                                      ctypes.byref(info),
                                      ctypes.sizeof(info),
                                      FileProcessIdsUsingFileInformation)
pidList = info.ProcessIdList[0:info.NumberOfProcessIdsInList]
print(pidList)

answered Nov 10, 2022 at 13:22

Robert's user avatar

RobertRobert

1314 bronze badges

There is a tool FILEMON and shows open files and handles. Its hard to keep up with its display if you watch it live, it does so quickly. But you can stop it from displaying live and you can watch all file open/write activity. Now owned by Microsoft but originally by Sysinternals

answered May 27, 2010 at 16:15

user44304's user avatar

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

  • Windows консоль права на папку
  • Windows комментарии в bat файле
  • Windows как читается на русском языке
  • Windows как узнать кто использует файл
  • Windows какая программа слушает порт