PoshCode Logo PowerShell Code Repository

Receive-Stream (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1688"></script>download | new post

A very simple stream-reader implementation (with no error handling) suitable for simple interactive script task …

  1. function Receive-Stream {
  2. #.Synopsis
  3. #  Read a stream to the end and close it
  4. #.Description
  5. #  Will read from a byte stream and output a string or a file
  6. #.Param reader
  7. #  The stream to read from
  8. #.Param fileName
  9. #  A file to write to. If this parameter is provided, the function will output to file
  10. #.Param encoding
  11. #  The text encoding, if you want to override the default.
  12. param( [System.IO.Stream]$reader, $fileName, $encoding = [System.Text.Encoding]::GetEncoding( $null ) )
  13.    
  14.    if($fileName) {
  15.       $writer = new-object System.IO.FileStream $fileName, "Create"
  16.    } else {
  17.       [string]$output = ""
  18.    }
  19.        
  20.    [byte[]]$buffer = new-object byte[] 4096
  21.    [int]$total = [int]$count = 0
  22.    do
  23.    {
  24.       $count = $reader.Read($buffer, 0, $buffer.Length)
  25.       if($fileName) {
  26.          $writer.Write($buffer, 0, $count)
  27.       } else {
  28.          $output += $encoding.GetString($buffer, 0, $count)
  29.       }
  30.    } while ($count -gt 0)
  31.  
  32.    $reader.Close()
  33.    if(!$fileName) { $output }
  34. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me