使用 StreamWriter() 写入与 StreamReader() 相同的文件 [英] Use StreamWriter() to write to the same file as StreamReader()

查看:56
本文介绍了使用 StreamWriter() 写入与 StreamReader() 相同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在多个文件中查找并替换某个字符串.其中一些文件可能相对较大,因此我使用了 System.IO 命名空间中的 StreamReader 类.

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 System.IO namespace.

我遇到的问题是我不想将新值写入新文件(这是我目前拥有的).我只想更新"当前文件.

The issue I have is that I don't want to have to write the new values to a new file (which is what I have currently). I want to just "update" the current files.

$currentValue = "B";
$newValue = "A";

# Loop through all of the directories and update with new details. 
foreach ($file in $Directories) {
    $streamReader = New-Object System.IO.StreamReader -Arg "$file"
    $streamWriter = [System.IO.StreamWriter] "$file"
    # Switching $streamWriter to the below works.
    # $streamWriter = [System.IO.StreamWriter] "C:\Temp\newFile.txt"

    while($line = $streamReader.ReadLine()){
        # Write-Output "Current line value is $line";
        $s = $line -replace "$currentValue", "$newValue"
        # Write-Output "The new line value is $s"
        $streamWriter.WriteLine($s);
    }

    # Close the streams ready for the next loop.
    $streamReader.close();
    $streamWriter.close();
}

Write-Output "The task has complete."

有谁知道我可以如何进行上述操作?

Does anyone know how I could go about doing the above?

推荐答案

您不能同时读取和写入同一个文件.不适用于 StreamReaderStreamWriter,也不适用于任何其他常用方法.如果您需要修改现有文件并且不能(或不想)将其全部内容读入内存,您必须将修改后的内容写入临时文件,然后用两个文件都关闭后的临时文件.

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.

示例:

$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

这篇关于使用 StreamWriter() 写入与 StreamReader() 相同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆