138

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.

Jens Erat
  • 18,485
  • 14
  • 68
  • 80
John K
  • 2,900

10 Answers10

197

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.

Kevin Panko
  • 7,466
user257114
  • 1,979
  • 2
  • 11
  • 2
65

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

marsh-wiggle
  • 3,134
34

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

Ice
  • 679
22

Try Easy File Locker (freeware).

enter image description here

per1234
  • 163
David
  • 292
18

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
  • 181
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

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"
Ciove
  • 161
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
  • 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
  • 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.

CJM
  • 2,627