How to purposefully exclusively lock a file?

Solution 1:

Try Easy File Locker (freeware).

enter image description here

Solution 2:

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.

Solution 3:

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