Last active
February 4, 2025 10:01
How to safely read from / write to text files using .NET in PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$outputFilePath = "drive:\path\to\file.txt" # will work with files on remote file servers (-> UNC paths), too | |
try { | |
if (Test-Path -Path $outputFilePath -PathType Leaf) { | |
try { | |
$fStream = [System.IO.FileStream]::New($outputFilePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) # exclusively open file for read/write | |
} catch [System.IO.IOException] { | |
throw [System.Management.Automation.RuntimeException]::New("The file '" + $outputFilePath + "' could not be opened - aborted!", $_.Exception) | |
} | |
} else { | |
try { | |
$fStream = [System.IO.File]::Create($outputFilePath) # create new file | |
} catch { | |
throw [System.Management.Automation.RuntimeException]::New("The file '" + $outputFilePath + "' could not be created - aborted!", $_.Exception) | |
} | |
} | |
if ($fStream.CanWrite) { # checking for write access also includes read access, so there's no need to check both | |
$enc = [System.Text.Utf8Encoding]::New() # let's assume the file content is encoded in UTF-8 | |
# just an example of how to read data from the file, using the FileStream object we instantiated above | |
if ($fStream.Length -gt 0) { | |
$sBytes = [Byte[]]::New($fStream.Length) | |
[Int]$bRead = 0 | |
do { | |
$fStream.Read($sBytes, $bRead, $fStream.Length) | Out-Null | |
} while ($bRead -gt 0) | |
[String]$dataStr = $enc.GetString($sBytes).Trim() 2>$null | |
# ... do something with the read data ... | |
Write-Host $("File data: `r`n" + $dataStr) | |
} | |
# Write something to the file; in this demo, it's a timestamp | |
$curDate = Get-Date | |
$dateStr = $(if ($fStream.Length -gt 0) { "`r`n" } else { "" }) + $curDate.Ticks.ToString() + " (" + ("{0:dd.MM.yyyy}" -f $curDate) + ")" | |
$fStream.Seek(0, [System.IO.SeekOrigin]::End) | Out-Null # add the content to the end of the file | |
$fStream.Write($enc.GetBytes($dateStr), 0, $enc.GetByteCount($dateStr)) | |
} else { | |
throw [System.Management.Automation.RuntimeException]::New("The file '" + $outputFilePath + "' could not be modified - aborted!") | |
} | |
} finally { | |
if ($fStream) { | |
# cleanup | |
try { | |
$fStream.Close() | |
$fStream = $null | |
} catch { | |
# ignore errors | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment