How to rewrite this C# code that deals with a Stream and a byte buffer

523 views Asked by At

I have this C# code:

const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
{
   outstream.Write(buffer, 0, count);
}

I need to rewrite it in F#. I can do it like this:

let bufferLen : int = 4096
let buffer : byte array = Array.zeroCreate bufferLen
let count : int = 0

let mutable count = stream.Read(buffer, 0, bufferLen)
if count > 0 then
   outstream.Write(buffer, 0, count)

while (count > 0) do
   count <- stream.Read(buffer, 0, bufferLen)
   outstream.Write(buffer, 0, count)

But may be there is a more functional way ?

1

There are 1 answers

0
Random Dev On BEST ANSWER

Aside from Patryk's point on comment:

It's a really imperative problem so it will not get much prettier.

The only thing I would try to change is the repeated read/writes - maybe like this:

let copyInto (outstream : System.IO.Stream) (stream : System.IO.Stream) =
    let bufferLen : int = 4096
    let buffer : byte array = Array.zeroCreate bufferLen

    let rec copy () =
        match stream.Read(buffer, 0, bufferLen) with
        | count when count > 0 ->
            outstream.Write(buffer, 0, count)
            copy ()
        | _ -> ()

    copy ()