I see I got beat to it:)

let streamCopy (chunkSize:int) (src:#System.IO.Stream) (dest:#System.IO.Stream) =

let chunk = Array.zeroCreate chunkSize

let rec loop totalTransfered (src:#System.IO.Stream) (dest:#System.IO.Stream) =

match src.Read(chunk,0,chunkSize) with

| 0 -> totalTransfered

| read ->

dest.Write(chunk,0,read)

loop (totalTransfered+read) src dest

loop 0 src dest

You don't need to make chunk <b><i>mutable<i></b> since the reference that chuck points to will not change only the contents of the array it points to will. Also by using an internal rec function instead you can allocate the chunk once for all the copies you want to do in the loop construct. I also used the match construct to simply the control flow from the src.Read(...) -Patrick

By on 7/16/2009 2:19 PM ()

Also by using an internal rec function instead you can allocate the chunk once for all the copies you want to do in the loop construct.

Ah yes, that was missing too :P.

By on 7/16/2009 2:22 PM ()

Thank you both for the suggestions. Here is the function cleaned up:

1
2
3
4
5
6
7
8
9
let streamCopy bufferSize a b =
  let buffer = Array.zeroCreate bufferSize
  let rec copy (a:Stream) (b:Stream) =
    match a.Read(buffer, 0, bufferSize) with
    | 0 -> ()
    | readSize -> 
      b.Write(buffer, 0, readSize)
      copy a b
  copy a b
By on 7/16/2009 3:33 PM ()

bytes doesn't have to be mutable, since the reference to the array doesn't change, just the contents. It should work.

A match on a.Read might be nicer, and would avoid the last zero write:

1
2
3
4
5
6
let rec streamTransfer chunk (a: Stream) (b: Stream) = 
    let bytes = Array.zeroCreate chunk 
    match a.Read(bytes, 0, chunk) with
    | 0    -> ()
    | read -> b.Write(bytes, 0, read)
              streamTransfer chunk a b
By on 7/16/2009 2:18 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper