PowerShell Closing FileStream

心已入冬 提交于 2021-01-29 04:57:46

问题


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.

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()

回答1:


In PowerShell, the > character is used for redirection, to pipe the text from one command into a file, or another stream.

With your line of

}While($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.

Change that > to -GT, which is the PowerShell comparison operator for greater than, and you should get the results you're expecting.

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.



来源:https://stackoverflow.com/questions/34357609/powershell-closing-filestream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!