Reputation: 119
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
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 |
|
Assuming your script opens the file first, file locking issues can happen in these cases:
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:
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:
ReadWrite
is the best you can do to ensure maximum compatibility when you need to read the file.Upvotes: 1