Open File Exclusively

by Aug 19, 2011

To open a file in a locked state so no one else can open, access, read, or write the file, you can use the low-level .NET methods like this:

$path = 'c:\somefile.txt'    # MUST EXIST!
$file = []::Open($path, 'Open', 'Read', 'None')
$reader = New-Object System.IO.StreamReader($file)
$text = $reader.ReadToEnd()
Read-Host 'Press ENTER to release file!'

This will lock a file and read its content. To illustrate the lock, the file will remain locked until you press ENTER.

Twitter This Tip!
ReTweet this Tip!