如何重写处理Stream和字节缓冲区的C#代码

时间:2015-06-23 11:04:55

标签: f# c#-to-f#

我有这个C#代码:

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);
}

我需要在F#中重写它。我可以这样做:

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)

但是可能有一种更实用的方式吗?

1 个答案:

答案 0 :(得分:4)

除了Patryk的评论观点:

这是一个非常迫切的问题,所以它不会变得更漂亮。

我唯一想改变的是重复读/写 - 也许是这样:

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