Windows file open lock

How to View and Close Open Files in Windows Server SMB Share?

Windows file server administrators often have to force close the shared files that are open simultaneously by multiple users. This usually happens if the desktop software doesn’t work as expected, the user logs off incorrectly, or when the user opened a file and forgot to close it (went home, on vacation, etc.). In all these cases, the file on the shared network folder is still open (and locked) and cannot be modified by other users. Other users can see such a message when trying to open a locked file (depending on the application used): The document filename is locked for editing by another user. To open a read-only copy of his document, click…

In this article we’ll show you how to get the list of open files on a Windows file server, find out which user locked a file on a shared folder, and how to close (reset) file sessions to unlock open files.

View Open Files on a Shared Network Folder on Windows Server

You can get the list of files opened by users on Windows file server using the built-in Computer Management ( compmgmt.msc ) graphic snap-in.

Open the Computer Management console on your file server (or connect to the server remotely from the management console running on your computer) and go to System Tools -> Shared Folders -> Open files. A list of open files on current SMB server is displayed on the right side of the window. The list contains the local path to the file, the name of the user account that opens the file, the number of locks and the mode in which the file is opened (Read or Write+Read).

You can get the same list of open files using the built-in openfiles.exe console tool. For example, using the following command you can get the Session ID, username and full local path to the open file:

openfiles /Query /fo csv |more

You can display a list of open files on a remote server. For example, you need to list all open files in shared folders on the lon-fs01 host:

openfiles /Query /s lon-fs01 /fo csv

How to Find Out Who is Locking a File in a Shared Folder?

To identify the user who opened (locked) the filename.docx file on the shared network folder on the remote server lon-fs01, run this command:

openfiles /Query /s lon-fs01 /fo csv | find /i «filename.docx»

You can specify only a part of the file name. For example, you need to find out who opened an XLSX file containing “sale_report” in its name. Use the following pipe:

openfiles /Query /s lon-fs01 /fo csv | find /i «sale_report»| find /i «xlsx»

Of course you can find this file in the Computer Management GUI, but it’s less convenient (this console doesn’t provide search feature).

How to Forcibly Close an Open File on a SMB Share?

To close an open file, find it in the list of files in Open File section and select Close Open File in the context menu.

If there are hundreds of open files on your file server, it won’t be easy to find the specific file in the console. It is more convenient to use the Openfiles command line tool. As we have already told, it returns the session ID of the open file. Using this session ID you can force close the file by resetting the SMB connection.

Читайте также:  Windows run program from cmd

First, you need to find the session ID of the open file:

openfiles /Query /s lon-fs01 /fo csv | find /i «farm»| find /i «.xlsx»

Disconnect the user from file using the received SMB session ID:

openfiles /Disconnect /s lon-fs01 /ID 617909089

You can forcefully reset all sessions and unlock all files opened by a specific user:

openfiles /disconnect /s lon-fs01/u corp\mjenny /id *

Get-SMBOpenFile: Find and Close Open File Handlers Using PowerShell

New cmdlets to manage shares and files on an SMB server appeared in PowerShell version for Windows Server 2012/Windows 8. These cmdlets can be used to remotely close network connections to an open file.

You can get a list of open files using the Get-SMBOpenFile cmdlet. Close-SmbOpenFile is used to close/reset the connection to a remote file.

To display a list of open files on the Windows SMB server, run the command:

The command returns the file ID, session ID and full file name(path).
You can display a list of open files with user and computer names (IP addresses):

You can list all files opened by a specific user:

Get-SMBOpenFile –ClientUserName «corp\mjenny»|select ClientComputerName,Path

or from a specific computer/server:

Get-SMBOpenFile –ClientComputerName 192.168.1.190| select ClientUserName,Path

You can display a list of open files by pattern. For example, to list all exe files opened from the shared folder:

or open files with a specific name:

The Close-SmbOpenFile cmdlet is used to close the open file handler. You can close the file by ID:

Close-SmbOpenFile -FileId 4123426323239

But it is usually more convenient to close the file by name:

Get-SmbOpenFile | where <$_.Path –like "*annual2020.xlsx">| Close-SmbOpenFile -Force

With the Out-GridView cmdlet, you can make a simple GUI form for finding and closing open files. The following script will list open files. You should use the built-in filters in the Out-GridView table to find open files for which you want to reset the SMB sessions. Then you need to select the required files and click OK. As a result, the selected files will be forcibly closed.

Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessionID| Out-GridView -PassThru –title “Select Open Files”|Close-SmbOpenFile -Confirm:$false -Verbose

How to Close Open Files on Remote Computer Using PowerShell?

The Get-SMBOpenFile and Close-SmbOpenFile cmdlets can be used to remotely find and close open (locked) files. First, you need to connect to a remote Windows SMB server via a CIM session:

$sessn = New-CIMSession –Computername lon-fs01

The following command will find the SMB session for the open file pubs.docx and close the file session.

Get-SMBOpenFile -CIMSession $sessn | where <$_.Path –like "*pubs.docx">| Close-SMBOpenFile -CIMSession $sessn

Confirm closing of the file by pressing Y . As a result, you have unlocked the file. Now other users can open it.

With PowerShell, you can close SMB sessions and unlock all files that a specific user has opened (a user went home and didn’t release the open files). For example, to reset all file sessions of the user mjenny, run this command:

Get-SMBOpenFile -CIMSession $sessn | where <$_.ClientUserName –like "*mjenny*">|Close-SMBOpenFile -CIMSession $sessn

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.

Читайте также:  Echo экранирование кавычек linux

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.

Release a File Lock in Windows

By Mitch Bartlett 10 Comments

If you work in IT, you’re probably familiar with Microsoft Windows users constantly locking files where others are not able to edit them. The problem of locked files seems to be most common with Microsoft Excel users.

It’s very common for users to leave an Excel spreadsheet open, causing an “Excel is locked for editing by another user” error to display for other users attempting to make changes to the spreadsheet.

If you have admin rights, you can force a disconnect and release the file lock using these steps.

Note: If you do not have permissions to release file locks, you may want to ask a person who does to grant you access or ask them to perform these steps.

  1. Hold the Windows Key and press “R” to bring up the Windows Run dialog screen.
  2. Type “mmc“, then press “Enter“.
  3. Go to “File” > “Add/Remove Snap-in…“.
  4. Scroll down and select “Shared Folders“, then choose “Add“.
  5. Select “Local computer” if you are logged into the computer or server where the file resides. Otherwise, select “Another computer“, then type the Computer Name of the other computer. You may also select “Browse…” to find the computer name.
  6. Select “Finish“.
  7. Select “OK“.
  8. Expand “Shared Folders“, then select “Open Files“.
  9. Find the file that is locked, then right-click it and choose “Close Open File“.

Now if you have the other user close the application, then re-open the file, they should be able to edit it without a locking issue.

This post applies to Windows 10, 7, 8, Server 2008, and Server 2012.

Locking files using C++ on Windows

I have a program writing/reading from a file, and I want to lock the file for other instances of my application. How can I do it (in c++ visual studio 2003)? I tried using the _locking() but then also I myself cannot reach the file when trying to read/write (in the same instance). I know there’s an option of LockFile() but have no idea how to set it properly. Please help me.

Читайте также:  Загрузка с флешки windows 10 настройка bios gigabyte

3 Answers 3

You can simply use the Win32 API CreateFile and then specify no sharing rights. This will ensure that no other processes can access the file.

The dwShareMode DWORD specifies the type of sharing you would like, for example GENERIC_READ. If you specify 0 then that means no sharing rights should be granted.

If you want to only lock a certain part of the file you can use LockFile or LockFileEx.

You want LockFileEx() (exclusive file locking). Have a look at this discussion from Secure Programming Cookbook for C and C++.

After searching online for a while, I didn’t find any good examples.

Here are two calls to CreateFile with the intent of locking the file for the life of a process. I use this along side the CLimitSingleInstance that uses CreateMutex for a global named mutex.

The first call to CreateFile attempts to open it, the second one creates it if necessary. I have a little bit more thorough implementation. I implemented it in Qt, hence the qCritical() instead of std::cout and the QDir::tempPath() instead of getting that some other way.

Here is what you would have at the top of your main function:

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.

Command-line tool for finding out who is locking a file

I would like to know who is locking a file (win32). I know about WhoLockMe, but I would like a command-line tool which does more or less the same thing.

I also looked at this question, but it seems only applicable for files opened remotely.

7 Answers 7

Handle should do the trick.

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.

THis has helped me sooooo many times.

If you want to find what program has a handle on a certain file, run this from the directory that Handle.exe is extracted to. Unless you’ve added Handle.exe to the PATH environment variable. And the file path is C:\path\path\file.txt», run this:

This will tell you what process(es) have the file (or folder) locked.

Handle didn’t find that WhatsApp is holding lock on a file .tmp.node in temp folder. ProcessExplorer — Find works better Look at this answer https://superuser.com/a/399660

Computer Management->Shared Folders->Open Files

In my case Handle.exe did not help. Simple program from official Microsoft called Process Explorer was useful. Just open as administrator and press Ctrl+f , type part of file name it will show process using file.

I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.

Additionally, it offers actions to do to the locked file in question such as deleting it.

Unlocker helps delete locked files with error messages including «cannot delete file,» and «access is denied.» Video tutorial available.

Some errors you might get that Unlocker can help with include:

  • 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.
Оцените статью