129

I want to hold an exclusive lock on a file so it cannot be read or written by anything else. Is there a simple Windows tool or command to do this?

I suppose the tool or utility would implement the LockFileEx Windows Function.

Note: I've tried text editors like Notepad and Notepad++ on a text file but they don't hold an exclusive lock on it.

5
  • Why not just make one? Also, how long should they hold the lock? Should they wait for some event?
    – user541686
    Commented Jun 9, 2011 at 2:38
  • 7
    I considered programming one but figured there's a quick tool, editor or command I can use. On superuser not all users are programmers. bit.ly/lXT6ey I didn't want to go the Stackoverflow route with this question. Am testing the behaviour of an app when it can't access files.
    – John K
    Commented Jun 9, 2011 at 2:53
  • I might be able to make one for you -- just lemme know when the lock should be released.
    – user541686
    Commented Jun 9, 2011 at 2:57
  • see also my similar question superuser.com/questions/519389/flock-command-for-windows
    – eadmaster
    Commented Dec 18, 2012 at 2:50
  • Apparently, editors such as Notepad and Notepad++ don't even keep the file open non-exclusively.
    – John
    Commented Aug 27, 2014 at 15:31

10 Answers 10

22

Try Easy File Locker (freeware).

enter image description here

7
  • Does not work on Windows 2003 Commented Oct 29, 2014 at 14:38
  • 25
    This application doesn't appear to "Lock" files so much as change the permission on the file. This is an important distinction if you're trying to test how your application handles files being actively opened/locked by another application. In my case this application did not work. The 'notepad > file' solution should be the answer here. Commented Jul 20, 2015 at 14:48
  • 2
    DOES NOT WORK ON Windows 10. And uninstallable. Beware!! Commented Oct 8, 2018 at 6:16
  • This app caused multiple blue screen crashes on Windows 10. This app is also designed for creating inaccessible files via permission changes, not file locking by processes. Using FileLocker from @RRKbabxW3's answer worked perfectly. Commented Feb 5, 2019 at 2:49
  • 1
    Goes to blue screen of death on Windows 10.
    – TonySalimi
    Commented Sep 13, 2019 at 12:30
193

Simpler solution: In the directory of interest run from cmd line:

notepad >filetolock

As re-directed stdout, it will remain locked until the application (notepad) is terminated.

Note that the "filetolock" will be overwritten by the re-direct, so you probably don't want to use an existing file of any importance. An empty "filetolock" won't matter to the application you're trying to test, as the app won't be able to open it anyway.

18
  • 61
    use append redirect instead to now overwrite filetolock: notepad >>filetolock
    – eadmaster
    Commented Apr 18, 2014 at 1:38
  • 5
    very useful solution, no need to install anything
    – Aprillion
    Commented May 1, 2014 at 16:06
  • 7
    This is a much better solution than downloading more freeware.
    – BenCr
    Commented Oct 6, 2014 at 12:30
  • 11
    Still works on Windows 10. Should be the accepted answer Commented Oct 14, 2015 at 9:38
  • 16
    For some reason this has to be executed in cmd.exe. It doesn't work in PowerShell. File is created and notepad is opened but you can still delete file despite notepad being open. I tested this on both Windows Server 2012 and Windows 10. Commented Mar 23, 2017 at 6:56
60

Lock a file without 3rd party tools, no changes to the file being locked and file can't even be copied

This PowerShell script is a quote from an answer to a similar question.

# Specify the file name
$fileName = "C:\myfile.txt"

# Open the file in read only mode, without sharing (I.e., locked as requested)
$file = [System.io.File]::Open($fileName, 'Open', 'Read', 'None')

# Wait in the above (file locked) state until the user presses a key
Write-Host "Press any key to continue ..."
$null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

# Close the file
$file.Close()

Edit: quoting a very usefull comment:

While testing this I found that you can also just use

[System.io.File]::Open('c:\myfile.txt', 'Open', 'Read', 'None') 

which will keep the file open until you close PowerShell

5
  • 2
    i found this as the only working solution. Both notepad and EasyFileLocker methods doesn't totally lock the file and still can be copied (tested on Windows 10)
    – HypeZ
    Commented May 16, 2016 at 8:26
  • For Powershell ISE use [void](Read-Host 'Press Enter to continue') instead of $host.UI.RawUI.ReadKey(...) as ReadKey is not supported in the pseudo-console in Powershell ISE.
    – Simon Elms
    Commented Sep 7, 2016 at 4:14
  • 4
    While testing this I found that you can also just use [System.io.File]::Open('c:\myfile.txt', 'Open', 'Read', 'None') which will keep the file open until you close PowerShell
    – user665780
    Commented Sep 15, 2020 at 14:54
  • Does this prevent everyone from reading or writing the file? i.e., if I have a powershell script, generally I'll want to [a] lock the file, [b] make changes to it, then [c] unlock it. it seems to me that with this method, [b] will be blocked too? Commented Apr 26 at 19:33
  • after some testing, I am correct -- locking the file prevents not only other users and processes on other machines from accessing it; it prevents other processes in the same powershell script from accessing it. Commented Apr 26 at 19:40
34

Open it with MS-Excel... this app locks a file while open.

1
  • 12
    And I thought Excel was useful before! Commented Oct 4, 2012 at 19:58
17

FileLocker is a freeware/open source command line tool.

Usage:

FileLocker [/T LockTime] [/I] [/K] [/Q] file [file...]

/T LockTime     Time in milliseconds to lock the file
/I              Infinite locking until process is killed (default)
/K              Lock file until key is pressed
/Q              Be quiet.
3
  • 1
    This worked for me where other solutions did not
    – cowlinator
    Commented Jan 31, 2018 at 0:46
  • 4
    Note that on Windows 10, it must be run As Administrator.
    – cowlinator
    Commented Jan 31, 2018 at 0:53
  • compared to lots of other googled solution, this immediately worked, and also it completely locked the file (also read access was locked, not just writing).
    – ndbd
    Commented Nov 20, 2020 at 20:35
6

I cannot write comments, so I add my info this way:

https://stackoverflow.com/questions/5860542/how-can-i-simulate-a-locked-file-one-which-has-a-write-lock

EDIT: summary of the other question:

  • pause command: ( >&2 pause ) >> file2lock.txt

  • MS programs like word or excel locks too (works for text-files)

  • Programatically use LockFileEx (windows API) with LOCKFILE_EXCLUSIVE_LOCK and LOCKFILE_FAIL_IMMEDIATELY

1
  • This is the only one that worked for me in Windows Server 2019+
    – Markive
    Commented Mar 6, 2023 at 7:44
3

I second the solution by marsh-wiggle. Here's my version of the script:

# This is lock_file.ps1
[CmdletBinding()]
Param(
  [Parameter(Mandatory=$False)]
  [string]$my_file_path
)
if (!$my_file_path){
   Write-Host "Parameter my_file_path is missing, quitting."
   [Environment]::Exit(1)
}
$my_file_exists = Test-Path $my_file_path -pathType Leaf
If ($my_file_exists) {
   #Open the file in read only mode, without sharing (I.e., locked as requested)
   $my_open_file = [System.io.File]::Open($my_file_path, 'Open', 'Read', 'None')
   #Wait in the above (file locked) state until the user presses a key
   Write-Host "Press any key to continue ..."
   $null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
   #Close the file
   $my_open_file.Close()
} else {
   Write-Host "Parameter mismatch, file doesn't exist." 
}

You can call it from cmd like this:

powershell -ExecutionPolicy Unrestricted -file lock_file.ps1 "path\to\file_to_lock.txt"
1

Here is how I replicate user behavior of a locked file for bug testing.

Dim s As New StreamReader("C:\test\sampleFile.txt")

I add that line to my unit test to lock the file and then run the test in debug mode to replicate bad behavior when a given file is locked.

I still do not know how my business users are locking the given file. As you said, notepad cannot lock it exclusively.

Luckily, declaring a streamreader locks a file exclusively unless you specify otherwise.

0

For testing Robocopy ERROR "access denied" I just removed read-access for the user. Would that work?

For windows 10 this can be readily done from the command line

chmod 'u-r' lockfile

For windows 7, you can use file explorer security properties.

-2

Replace 'Your-Password-Here' with your password, and save this script as Locker.bat

*cls
@ECHO OFF
title Folder Locker
if EXIST "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" goto UNLOCK
if NOT EXIST Locker goto MDLOCKER
:CONFIRM
echo Are you sure u want to Lock the folder(Y/N)
set/p "cho=>"
if %cho%==Y goto LOCK
if %cho%==y goto LOCK
if %cho%==n goto END
if %cho%==N goto END
echo Invalid choice.
goto CONFIRM
:LOCK
ren Locker "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
attrib +h +s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
echo Folder locked
goto End
:UNLOCK
echo Enter password to Unlock folder
set/p "pass=>"
if NOT %pass%==Your-Password-Here goto FAIL
attrib -h -s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
ren "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" Locker
echo Folder Unlocked successfully
goto End
:FAIL
echo Invalid password
goto end
:MDLOCKER
md Locker
echo Locker created successfully
goto End
:End*

When you run the batch file, it will present you with the 'Are you sure u want to Lock the folder(Y/N)' prompt; type Y and press enter and the folder will be locked.

Run the the batch file again, and enter your password and the folder and all your files will be unlocked again.

1
  • 2
    This only works on folders, and worse, it renames the folder. That won't do at all. Commented Feb 19, 2018 at 15:02

You must log in to answer this question.

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