How to purposefully exclusively lock a file?

91

25

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.

John K

Posted 2011-06-09T02:24:10.010

Reputation: 2 148

Apparently, editors such as Notepad and Notepad++ don't even keep the file open non-exclusively. – John – 2014-08-27T15:31:42.000

Why not just make one? Also, how long should they hold the lock? Should they wait for some event? – user541686 – 2011-06-09T02:38:23.387

6

I considered programming one but figured there's a quick tool, editor or command I can use. On superuser not all users are programmers. http://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 – 2011-06-09T02:53:20.433

I might be able to make one for you -- just lemme know when the lock should be released. – user541686 – 2011-06-09T02:57:59.090

see also my similar question http://superuser.com/questions/519389/flock-command-for-windows

– eadmaster – 2012-12-18T02:50:18.567

Answers

23

Try Easy File Locker (freeware).

enter image description here

David

Posted 2011-06-09T02:24:10.010

Reputation: 286

Does not work on Windows 2003 – Eric Bonnot – 2014-10-29T14:38:27.163

14This 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. – javajavajavajavajava – 2015-07-20T14:48:37.340

1DOES NOT WORK ON Windows 10. And uninstallable. Beware!! – Shahar Prish – 2018-10-08T06:16:59.743

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. – Jordan Mack – 2019-02-05T02:49:27.307

Goes to blue screen of death on Windows 10. – Gupta – 2019-09-13T12:30:03.377

143

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.

user257114

Posted 2011-06-09T02:24:10.010

Reputation: 1 431

6This is a much better solution than downloading more freeware. – BenCr – 2014-10-06T12:30:53.543

2Great sulution. The locked file can't be deleted, but it can be copied. – marsh-wiggle – 2015-01-05T13:23:07.457

11Still works on Windows 10. Should be the accepted answer – SoonDead – 2015-10-14T09:38:58.370

Extremely useful, works perfectly in Windows 8.1 too. – Spikeh – 2016-04-08T12:40:48.310

8For 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. – Ville Salonen – 2017-03-23T06:56:43.757

Great for testing exception handling for File.WriteAllText and co. – Alex Vang – 2017-09-20T10:00:52.903

2this method only place a write lock, not a read lock – MtwStark – 2018-01-11T15:34:08.283

Do not forget to run as Administrator. That did it for me. – Bonez024 – 2018-02-27T19:17:15.973

@VilleSalonen: any ideas why it doesn't work from PowerShell? I have found https://stackoverflow.com/questions/1215260/how-to-redirect-the-output-of-a-powershell-to-a-file-during-its-execution and the answers there (namely powershell notepad >filetolock and notepad | Out-File C:\path\to\filetolock) seem to be working without problems. I suspect, that the interpretation of > is internally differently dispatched in cmd and in PowerShell, but I cannot find any confirmation on that.

– D. Kovács – 2018-06-04T10:46:04.483

41use append redirect instead to now overwrite filetolock: notepad >>filetolock – eadmaster – 2014-04-18T01:38:30.310

5very useful solution, no need to install anything – Aprillion – 2014-05-01T16:06:04.193

33

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.

If you find it helpful, you may upvote the original answer and not this posting.

#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()

marsh-wiggle

Posted 2011-06-09T02:24:10.010

Reputation: 2 357

2i 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 – 2016-05-16T08:26:11.870

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. – SimonTewsi – 2016-09-07T04:14:26.163

26

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

Ice

Posted 2011-06-09T02:24:10.010

Reputation: 599

11And I thought Excel was useful before! – Scott Stafford – 2012-10-04T19:58:15.893

12

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.

RRKbabxW3

Posted 2011-06-09T02:24:10.010

Reputation: 121

1This worked for me where other solutions did not – cowlinator – 2018-01-31T00:46:37.063

3Note that on Windows 10, it must be run As Administrator. – cowlinator – 2018-01-31T00:53:51.217

4

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

Mayra Delgado

Posted 2011-06-09T02:24:10.010

Reputation: 151

2

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"

Ciove

Posted 2011-06-09T02:24:10.010

Reputation: 151

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.

kincaid

Posted 2011-06-09T02:24:10.010

Reputation: 11

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.

Cab

Posted 2011-06-09T02:24:10.010

Reputation: 1

-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.

John Doe

Posted 2011-06-09T02:24:10.010

Reputation: 1

2This only works on folders, and worse, it renames the folder. That won't do at all. – I say Reinstate Monica – 2018-02-19T15:02:36.607