- Файл заблокирован процессом Windows, как снять блокировку?
- Как разблокировать файл с помощью Process Explorer?
- Сброс дескриптора файла с помощью утилиты Handle
- How to Identify which Windows Process is Locking a File or Folder
- Symptoms
- How to Solve the Issue
- Identify what program is using a file
- Identify which handle or DLL is using a file
- Release the lock on the file or folder
- LockFile function (fileapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- Delete Locked Files and fix File Is Locked error in Windows 10
- Locked Files errors in Windows 10
- Is The File Really Open?
- Manually Change Attributes
- Is the File From Internet?
- Use Third-Party Software
Файл заблокирован процессом Windows, как снять блокировку?
Иногда при попытке удалить, переименовать или переместить какой-то файл в Windows вы можете получить сообщение, что файл занят/заблокирован/используется) другим процессом. Чаще всего имя программы, которая держит файл открытым указывается прямо в окне сообщения File Explorer. Чтобы снять блокировку файла достаточно просто закрыть эту программу. Но бывает ситуации, когда какой-то файл и библиотека используется неизвестным или системным процессом. В этом случае снять блокировку с файла немного сложнее.
Сообщение о блокировке файла может выглядеть по-разному. Например в следующем примере указан тип файла и с каким приложением он ассоциирован:
В этом случае вы можете легко понять какое приложение заблокировало файл и закрыть его.
Однако иногда можно увидеть более интересное сообщение, о том, что файл заблокирован неизвестным или системным процессом Windows. Это может быть, как процесс самой ОС Windows, так и другие процессе, работающий с правами System, например, антивирус, агент резервного копирования, база данных mssql и т.д.):
Попробуем разобраться, как понять какой программой, службой или системным процессом Windows занят файл, как разблокировать файл и можно ли разблокировать файл не закрывая родительский процесс.
Самый простой вариант разблокировать файл – завершить процесс, которые его заблокировал. Но это не всегда возможно, особенно на серверах.
Кроме того, это сторонняя утилита, при установке которой нужно быть внимательным, т.к. в процессе она предлагает установить пачку ненужные программы в нагрузку.
Когда процесс в Windows открывает файл, этому потоку ввода/вывода назначается файловый дескриптор (handler). Процесс и его дочерние процессы получают доступ к файлу по этому дескриптору. Через Window API вы можете послать сигнал файловой системе на освобождение данного дескриптора и снятие блокировки с файла.
Как разблокировать файл с помощью Process Explorer?
ProcessExplorer это бесплатная утилита из набора системных утилит Sysinternals, которую можно скачать на сайте Microsoft (https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer). Попробуем с помощью Process Explorer найти, какой процесс заблокировал определенный файл и освободить этот файл, сбросив файловый дескриптор процесса.
- ProcessExplorer не требует установки, просто скачайте распакуйте и запустите с правами администратора procexp.exe ;
- Выберите меню Find ->Find Handle or DLL (или нажмите Ctrl-F );
- Укажите имя файла, который нужно разблокировать и нажмите Search;
- Выберите нужный файл. Процесс, который открыл файлы будет выделен в дереве процессов. Можно завершить этот процесс, щелкнув по нему правой кнопкой и выбрав Kill Process Tree. Но можно попробовать закрыть дескриптор файла, не завершая процесс целиком. Дескриптор файла, который вы искали, автоматически выделяется в нижней панели Process Explorer. Щелкните по дескриптору правой кнопкой и выберите Close handle. Подтвердите закрытие файла.
Итак, вы закрыли дескриптор файла, не завершая родительский процесс. Теперь вы можете спокойно удалить или переименовать файл.
Сброс дескриптора файла с помощью утилиты Handle
Handle – это еще одна утилита командной строки из комплекта инструментов Sysinternals (доступна для скачивания на сайте Microsoft (https://docs.microsoft.com/en-us/sysinternals/downloads/handle. Она позволяет найти процесс, который заблокировал ваш файл и снять блокировку, освободив дескриптор.
- Скачайте и распакуйте архив с утилитой Handle;
- Запустите командную строку с правами администратора и выполните команду: handle64.exe > listproc.txt
Данная команда сохранит список открытых дескрипторов в файл. Можно вывести дескрипторы для каталога, в котором находится файл, который вы хотите изменить: Handle64.exe -a C:\Some\Path или конкретного процесса: handle64.exe -p winword.exe
- Откройте файл listproc.txt в любом текстовом редакторе и найдите строку, в которой указано имя заблокированного файла. Скопируйте ID дескриптора файла (значение в hex формате). Затем поднимитесь немного выше к разделу, в котором указан процесс, являющийся владельцем данного дескриптора и запишите его ID. Для процесса запущенного от имени системы скорее всего будет PID 4.
Если система отреагирует на закрытие файла корректно, вы разблокируете ваш файл без необходимости завершать процесс или перезагружать сервер/компьютер.
How to Identify which Windows Process is Locking a File or Folder
While attempting to delete, move, or rename a file or folder you get a Windows warning message; the Operating System refuses to complete the operation.
This article helps identifying the process that currently has a handle on the file or folder you are attempting a maintenance operation on.
Symptoms
When trying to delete, move, or rename a file you get a Windows system warning message:
- «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».
How to Solve the Issue
One of the easiest ways to handle locked files or folders is to use Microsoft Sysinternals Process Explorer.
Identify what program is using a file
Using Process Explorer there is a simple way to find the program:
- Open Process Explorer
- Running as administrator.
- On the toolbar, find the gunsight icon on the right.
- Drag the icon and drop it on the open file or folder that is locked.
- The executable that is using the file will be highlighted in the Process Explorer main display list.
Identify which handle or DLL is using a file
- Open Process Explorer
- Running as administrator.
- Enter the keyboard shortcut Ctrl+F.
- Alternatively, click the “Find” menu and select “Find a Handle or DLL”.
- A search dialog box will open.
- Type in the name of the locked file or other file of interest.
- Partial names are usually sufficient.
- Click the button “Search”.
- A list will be generated.
- There may be a number of entries.
Release the lock on the file or folder
To release the lock on the file you are attempting the maintenance operation on, you will need to kill the appropriate process. An individual program or handle in the list provided by Process Explorer can be killed by:
- Selecting the process/handle/program entry.
- Pressing the delete key.
Proceed with care when deleting handles as this may generate erratic behavior and instabilities may occur.
LockFile function (fileapi.h)
Locks the specified file for exclusive access by the calling process.
To specify additional options, for example creating a shared lock or for block-on-fail operation, use the LockFileEx function.
Syntax
Parameters
A handle to the file. The file handle must have been created with the GENERIC_READ or GENERIC_WRITE access right. For more information, see File Security and Access Rights.
The low-order 32 bits of the starting byte offset in the file where the lock should begin.
The high-order 32 bits of the starting byte offset in the file where the lock should begin.
The low-order 32 bits of the length of the byte range to be locked.
The high-order 32 bits of the length of the byte range to be locked.
Return value
If the function succeeds, the return value is nonzero (TRUE).
If the function fails, the return value is zero (FALSE). To get extended error information, call GetLastError.
Remarks
If the call to LockFile completes synchronously, a completion entry may not be queued when a completion port is associated with the file handle.
The UnlockFile function unlocks a file region locked by LockFile.
Locking a region of a file gives the threads of the locking process exclusive access to the specified region using this file handle. If the file handle is inherited by a process created by the locking process, the child process is not granted access to the locked region. If the locking process opens the file a second time, it cannot access the specified region through this second handle until it unlocks the region.
Locking a region of a file does not prevent reading from a mapped file view.
You can lock bytes that are beyond the end of the current file. This is useful to coordinate adding records to the end of a file.
Exclusive locks cannot overlap an existing locked region of a file. For more information, see LockFileEx.
If LockFile cannot lock a region of a file, it returns zero immediately. It does not block. To issue a file lock request that will block until the lock is acquired, use LockFileEx without the LOCKFILE_FAIL_IMMEDIATELY flag.
If a process terminates with a portion of a file locked or closes a file that has outstanding locks, the locks are unlocked by the operating system. However, the time it takes for the operating system to unlock these locks depends upon available system resources. Therefore, it is recommended that your process explicitly unlock all files it has locked when it terminates. If this is not done, access to these files may be denied if the operating system has not yet unlocked them.
In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.
Delete Locked Files and fix File Is Locked error in Windows 10
You know how much it irritates when you wish to move a file and you get a message saying the file is locked and you cannot move or delete it. This might happen due to the file really being in use with some application or due to its attributes’ settings. The reason might also be that Windows locked the file as it originated from an unsafe source such as the Internet.
Locked Files errors in Windows 10
This article aims to help you in case you are experiencing a problem with locked files and show you how to delete undeletable & locked files. Sometimes restarting your PC can make this error message go away – so that is something you want to try first and see if it works.
Is The File Really Open?
You need to see if the locked file is really open in any application. What happens actually is that when you open a file, Windows locks it for editing. This locking prevents editing the files concurrently from more than one place and more than one application. This also avoids two people seeing two different versions of the same file.
If you do not see any application using the file in question, open the Windows Task Manager (Press CTRL+ALT+DEL or right-click on the taskbar to select Task Manager). Check the processes tab to ascertain if there is any process running that might be related to the file type of locked file. If yes, close the process by right-clicking and selecting “End Process”
Note that you need to be sure about the processes you are ending as closing a Windows essential process may cause your system to hang or act unstable.
Manually Change Attributes
Every file under Windows has three active attributes: read-only, hidden and archive. A file marked for archive tells Windows that it is ready for backup. A file marked read-only will not accept any changes to its contents. A hidden file will not show up in Windows Explorer unless you have set up the option to show hidden files.
We have to deal with the read-only attribute in this case. It is not that you always cannot delete or move read-only files but if you are getting problems saying “this file is locked…”, remove the read-only attribute and try again. Sometimes, removing the read-only attribute helps in fixing the problem of locked files. To remove the read-only attribute, right-click on the file icon and select Properties. Under General tab, uncheck the box saying Read-Only.
Is the File From Internet?
While you are at the File Properties dialog box, check to see if the file originated from an unsafe source such as the Internet. If yes, you will see a message under the General tab that says the file has been blocked as a security measure. If yes, click on Unblock to fix the problem. Before clicking on Unblock, you should make sure you do not wish to open the file without checking it for viruses and other malware. You can run an anti-virus scan on the file to ascertain the same.
Use Third-Party Software
There are several third-party free file deleter software that can help you in unlocking files. Applications such as Free File Unlocker, Tizer UnLocker, Unlocker or UnlockIT help determine the file handles open in some application so that when prompted you can simply unlock them with one click.
Sometimes, you may have to click the Unlock button more than once to unlock the file completely. This behavior depends on the type of third-party applications you are using. Using third-party applications for locked files should be that last option as forcing unlock may make your computer unstable.
I hope this explains dealing with the problem of locked files. If you still face problems, please leave a note along with the operating system version so that we can assist you better.