Jake Roberts
Jake Roberts

Reputation: 119

StreamReader Correct way to read whole file without locking a file?

I am trying to read out of a license file written in xml in a way that will not lock the file in case the application happens to check at the same time. I have based the below code off of these two answers from Shay Levy and Jb Evain

I have confirmed that this is able to read from the file needed, and elements are able to be accessed and read from, but I wanted to confirm if reading the file in this way will not cause any file locking issues?

$FileStream = New-Object System.IO.FileStream $Path, 'Open', 'Read', 'ReadWrite'
$StreamReader = New-Object System.IO.StreamReader($FileStream)

$ReadFile = [xml] $StreamReader.ReadToEnd()

Upvotes: 2

Views: 91

Answers (1)

zett42
zett42

Reputation: 27806

Have a look at the access and share mode compatibility table. It is for the Win32 API, but applies to .NET as well because it calls down to Win32 CreateFile for file system access.

In your case the 3rd row applies (it contains a formatting error, which I've fixed below):

First call to CreateFile Valid second calls to CreateFile
GENERIC_READ
FILE_SHARE_READ
FILE_SHARE_WRITE
  • GENERIC_READ, FILE_SHARE_READ
  • GENERIC_READ, FILE_SHARE_READ, FILE_SHARE_WRITE
  • GENERIC_WRITE, FILE_SHARE_READ
  • GENERIC_WRITE, FILE_SHARE_READ, FILE_SHARE_WRITE
  • GENERIC_READ, GENERIC_WRITE, FILE_SHARE_READ
  • GENERIC_READ, GENERIC_WRITE, FILE_SHARE_READ, FILE_SHARE_WRITE

Assuming your script opens the file first, file locking issues can happen in these cases:

  • If another application tries to open the file without specifying any share mode flags, it will fail.
  • If another application tries to open the file with FILE_SHARE_WRITE only, it will fail (regardless of open mode). Other applications need to specify either FILE_SHARE_READ or FILE_SHARE_READ | FILE_SHARE_WRITE to successfully open the file.

On the other hand, if the file has been opened by another application first, your attempt at opening the file will fail if:

  • The other application didn't specify any share mode flags.
  • The other application has opened the file with FILE_SHARE_WRITE only. Other applications need to specify either FILE_SHARE_READ or FILE_SHARE_READ | FILE_SHARE_WRITE to let your script successfully open the file afterwards.

Conclusion:

  • Specifying file share mode ReadWrite is the best you can do to ensure maximum compatibility when you need to read the file.

Upvotes: 1

Related Questions