Use StreamWriter() to write to the same file as StreamReader()

前端 未结 2 1306
甜味超标
甜味超标 2021-01-15 13:55

I want to find and replace a certain string in a number of files. Some of these files can be relatively large so I am using the StreamReader class from the

2条回答
  •  半阙折子戏
    2021-01-15 14:27

    You can't read and write from/to the same file simultaneously. Not with StreamReader and StreamWriter, nor with any other usual method. If you need to modify an existing file and can't (or don't want to) read its entire content into memory you must write the modified content to a temporary file and then replace the original with the temp file after both files were closed.

    Example:

    $filename = (Get-Item $file).Name
    
    $streamReader = New-Object IO.StreamReader -Arg $file
    $streamWriter = [System.IO.StreamWriter] "$file.tmp"
    
    ...
    
    $streamReader.Close(); $streamReader.Dispose()
    $streamWriter.Close(); $streamWriter.Dispose()
    
    Remove-Item $file -Force
    Rename-Item "$file.tmp" -NewName $filename
    

提交回复
热议问题