How do I copy the contents of one stream to another?

后端 未结 13 2379
悲哀的现实
悲哀的现实 2020-11-21 22:11

What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?

13条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 22:47

    Since none of the answers have covered an asynchronous way of copying from one stream to another, here is a pattern that I've successfully used in a port forwarding application to copy data from one network stream to another. It lacks exception handling to emphasize the pattern.

    const int BUFFER_SIZE = 4096;
    
    static byte[] bufferForRead = new byte[BUFFER_SIZE];
    static byte[] bufferForWrite = new byte[BUFFER_SIZE];
    
    static Stream sourceStream = new MemoryStream();
    static Stream destinationStream = new MemoryStream();
    
    static void Main(string[] args)
    {
        // Initial read from source stream
        sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
    }
    
    private static void BeginReadCallback(IAsyncResult asyncRes)
    {
        // Finish reading from source stream
        int bytesRead = sourceStream.EndRead(asyncRes);
        // Make a copy of the buffer as we'll start another read immediately
        Array.Copy(bufferForRead, 0, bufferForWrite, 0, bytesRead);
        // Write copied buffer to destination stream
        destinationStream.BeginWrite(bufferForWrite, 0, bytesRead, BeginWriteCallback, null);
        // Start the next read (looks like async recursion I guess)
        sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
    }
    
    private static void BeginWriteCallback(IAsyncResult asyncRes)
    {
        // Finish writing to destination stream
        destinationStream.EndWrite(asyncRes);
    }
    

提交回复
热议问题