Author Posts

February 16, 2018 at 4:27 pm

Hi,

I'm trying to read a json-file, change the content and write it back.
Multiple processes are accessing the same file, so I need to lock the text file so no other thread or process can access it, read from it and write to it and unlock the file.

I tried using StreamWriter / StreamReader in various ways with no success:

 
$fileMode = [System.IO.FileMode]::Open
$fileAccess = [System.IO.FileAccess]::ReadWrite
$fileShare = [System.IO.FileShare]::None
$fileStream = New-Object -TypeName System.IO.FileStream $FilePath, $fileMode, $fileAccess, $fileShare

$reader = New-Object -TypeName System.IO.StreamReader -ArgumentList $fileStream

$encoding = [System.Text.Encoding]::Unicode                
$writer = New-Object System.IO.StreamWriter $fileStream, $encoding

$configuration = $reader.ReadToEnd() | ConvertFrom-Json

# Manipulating $config ...

$json = $configuration | ConvertTo-Json -Depth 10
$writer.Write($json)

$reader.Close()
$writer.Dispose()
$fileStream.Dispose()

This works, but appends the content to the file. I need to overwrite the content.
So I tried using a different StreamWriter constructor:

$fileMode = [System.IO.FileMode]::Open
$fileAccess = [System.IO.FileAccess]::ReadWrite
$fileShare = [System.IO.FileShare]::None
$fileStream = New-Object -TypeName System.IO.FileStream $FilePath, $fileMode, $fileAccess, $fileShare

$writer = New-Object System.IO.StreamWriter $fileStream, $false, $encoding

$writer.Write("Hello World")

$writer.Dispose()
$fileStream.Dispose()

This just does nothing. No exception is thrown, but the file is not changed.

What am I doing wrong here? The New-Object in the second example returns a StreamWriter-Object, but I can't use it to write to the stream.

February 16, 2018 at 9:06 pm

You could try the sequence: Open reader, read into memory, close reader. Open writer, overwrite file, close writer.
or
You could write out to a temp file and then rename it. It would be impossible to read a file and (over)write it out at the same time.