我正在处理一些非常大的文件来查找和替换字符串,所以我需要使用StreamReader和StreamWriter。而且我还需要支持多种编码。我有过
$reader = [IO.StreamReader]::New("\\Mac\Support\Journal Tools\Aaron\ANSI.txt")
$writer = [IO.StreamWriter]::New("\\Mac\Support\Journal Tools\Aaron\stream.txt", $reader.CurrentEncoding)它不会抛出任何类型的错误,但无论编码的源码是什么,输出文件始终是“System.Text.UTF8Encoding”。显然,我遗漏了一些基本的东西,但缺少抛出的错误让我感到困惑。
编辑:我尝试使用上面的构造函数强制使用ASCII,如下所示
$writer = [IO.StreamWriter]::New("\\Mac\Support\Journal Tools\Aaron\stream.txt", [System.Text.ASCIIEncoding])但不知何故,输出仍然是UTF8,但没有错误。越来越好奇。
编辑2:因此,基于注释,我尝试强制使用ASCII,并在此处添加了我正在使用的代码,以查看结果文件是如何编码的。也许这就是我错的地方?
$reader = [IO.StreamReader]::New("\\Mac\Support\Journal Tools\Aaron\ANSI.txt")
$writer = [IO.StreamWriter]::New("\\Mac\Support\Journal Tools\Aaron\stream.txt", [System.Text.Encoding]::ASCII)
try {
while (-not ($reader.EndOfStream)) {
$line = $reader.ReadLine()
$writer.WriteLine($line)
}
}
finally {
$reader.Close(); $reader.Dispose()
$writer.Close(); $writer.Dispose()
}
$reader.Close(); $reader.Dispose()
$writer.Close(); $writer.Dispose()
$test = [IO.StreamReader]::New("\\Mac\Support\Journal Tools\Aaron\stream.txt")
Write-Host "$($test.CurrentEncoding)!!!"
$test.Close(); $test.Dispose()最终,我需要能够将从.CurrentEncoding获得的文本表达式转换为构造函数的适当格式。有没有什么可用的函数,或者我要为这个转换创建我自己的表?
嗯,很奇怪。我有一个文件,我可以通过NotePad++验证它是否是UNICODE文件,但它仍然报告UTF8。
$reader = [IO.StreamReader]::New("\\Mac\Support\Journal Tools\Aaron\UNICODE.txt", $true)
Write-Host "$($reader.CurrentEncoding)"
$reader.Close(); $reader.Dispose()然而,这个小函数正确地返回了Unicode。
function Get-PxFileEncoding {
[CmdletBinding()]
param (
[parameter(Mandatory=$true)][String]$filePath
)
[Byte[]] $byte = get-content -path:$filePath -encoding:Byte -readCount:4 -totalCount:4
if ($byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf) {
$encoding = 'UTF8'
} elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff) {
$encoding = 'BigEndianUnicode'
} elseif ($byte[0] -eq 0xff -and $byte[1] -eq 0xfe) {
$encoding = 'Unicode'
} elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff) {
$encoding = 'UTF32'
} elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76) {
$encoding = 'UTF7'
} else {
$encoding = 'ASCII'
}
$encoding
}看起来这里可能有个bug。其他人可以验证上面3行代码是否为您返回Unicode吗?仅供参考,这是升级到PS5的Windows7虚拟机。
发布于 2018-01-05 02:18:09
[System.Text.ASCIIEncoding]是[type]类型的对象。你需要一个编码类型的对象。尝试使用[System.Text.Encoding]::ASCII、[System.Text.ASCIIEncoding]::ASCII或[System.Text.ASCIIEncoding]::new()
$writer = [IO.StreamWriter]::New("\\Mac\Support\Journal Tools\Aaron\stream.txt", [System.Text.ASCIIEncoding]::ASCII)https://stackoverflow.com/questions/48100506
复制相似问题