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

后端 未结 13 2362
悲哀的现实
悲哀的现实 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:51

    Unfortunately, there is no really simple solution. You can try something like that:

    Stream s1, s2;
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while (bytesRead = s1.Read(buffer, 0, buffer.Length) > 0) s2.Write(buffer, 0, bytesRead);
    s1.Close(); s2.Close();
    

    But the problem with that that different implementation of the Stream class might behave differently if there is nothing to read. A stream reading a file from a local harddrive will probably block until the read operaition has read enough data from the disk to fill the buffer and only return less data if it reaches the end of file. On the other hand, a stream reading from the network might return less data even though there are more data left to be received.

    Always check the documentation of the specific stream class you are using before using a generic solution.

提交回复
热议问题