StreamWriter WriteLine 如何在 Powershell 中附加而不是覆盖
How can StreamWriter WriteLine append instead of overwrite in Powershell
我试图让这个 StreamWriter WriteLine 将文本附加到已经存在的文件,但它正在覆盖它。
$inputFile = ".\input.txt"
$outputFile = ".\output.txt"
$reader = [io.StreamReader]::New($inputFile)
$writer = [io.StreamWriter]::New($outputFile)
while($reader.EndOfStream -ne $true) {
$readerLine = $reader.Readline()
if ($readerLine -like '#*') {
# skip line if it starts with #
}
elseif ($readerLine -like '') {
# skip empty lines
}
else {
$writer.WriteLine($readerLine);
}
}
$reader.Close();$reader.Dispose();
$writer.Close();$writer.Dispose();
从StreamWriter Constructor documentation开始,您需要启用追加。
$writer = [io.StreamWriter]::New($outputFile, $true)
我试图让这个 StreamWriter WriteLine 将文本附加到已经存在的文件,但它正在覆盖它。
$inputFile = ".\input.txt"
$outputFile = ".\output.txt"
$reader = [io.StreamReader]::New($inputFile)
$writer = [io.StreamWriter]::New($outputFile)
while($reader.EndOfStream -ne $true) {
$readerLine = $reader.Readline()
if ($readerLine -like '#*') {
# skip line if it starts with #
}
elseif ($readerLine -like '') {
# skip empty lines
}
else {
$writer.WriteLine($readerLine);
}
}
$reader.Close();$reader.Dispose();
$writer.Close();$writer.Dispose();
从StreamWriter Constructor documentation开始,您需要启用追加。
$writer = [io.StreamWriter]::New($outputFile, $true)