PowerShell关闭FileStream [英] PowerShell Closing FileStream
问题描述
我正在读取文件,对内容进行加密,然后使用PowerShell将密文写回到文件中.关闭FileStream对象($ inFS)后,它将在pwd(C:\ docs)中创建一个名为"0"的文件.我打开了文件,并在文件中写入了"32".
I am reading in a file, encrypting the contents, and writing the cipher text back out to a file using PowerShell. When the FileStream object ($inFS) is closed, it creates a file in the pwd (C:\docs) named "0". I opened the file and it had "32" written to it.
加密的内容被正确地写入另一个目录中的文件中.我以为缓冲区中还是有东西,所以我尝试了Flush()和Dispose(),但结果相同.为什么会这样?
The encrypted contents are being written to a file in a different directory with no problems. I thought maybe there was something in the buffer still so I tried Flush() and Dispose() but same results. Why is this?
$inFile = 'C:\docs\algorithm_fsa.c'
$inFS = New-Object FileStream($inFile, [FileMode]::Open)
DO
{
$count = $inFS.Read($data, 0, $blockSizeBytes)
$offset += $count
$outStreamEncrypted.Write($data, 0, $count)
$bytesRead += $blockSizeBytes
}While($count > 0)
$inFS.Close()
推荐答案
在PowerShell中,>
字符用于重定向,以将文本从一个命令传递到文件或另一个流中.
In PowerShell, the >
character is used for redirection, to pipe the text from one command into a file, or another stream.
您所在的行
}While($count > 0)
您正在指示PowerShell将 $ count
的内容写入标题为0的文件.无论您碰巧从哪个目录运行脚本,都将执行此操作.
You're instructing PowerShell to write the contents of $count
to a file titled 0. It does this, in whichever directory you happened to be running the script from.
将该>
更改为 -GT
,它是PowerShell的大于运算符,您应该得到期望的结果.
Change that >
to -GT
, which is the PowerShell comparison operator for greater than, and you should get the results you're expecting.
此外,此循环需要更改,因为当前它只会执行一次遍历文件,如 $ count>.0
不是可行的比较.将>替换为 -gt
后,您应该会满意.
Furthermore, this loop needs to be changed because currently, it would only execute one pass through the file, as $count > 0
is not an actionable comparison. Once you replace > with -gt
you should be good to go.
这篇关于PowerShell关闭FileStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!