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()
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
CreateFilefor file system access.In your case the 3rd row applies (it contains a formatting error, which I've fixed below):
FILE_SHARE_READ
FILE_SHARE_WRITE
Assuming your script opens the file first, file locking issues can happen in these cases:
FILE_SHARE_WRITEonly, it will fail (regardless of open mode). Other applications need to specify eitherFILE_SHARE_READorFILE_SHARE_READ | FILE_SHARE_WRITEto 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:
FILE_SHARE_WRITEonly. Other applications need to specify eitherFILE_SHARE_READorFILE_SHARE_READ | FILE_SHARE_WRITEto let your script successfully open the file afterwards.Conclusion:
ReadWriteis the best you can do to ensure maximum compatibility when you need to read the file.