Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the content of one stream into another stream in .net?

Tags:

.net

stream

I often run into the problem that I have one stream full of data and want to write everything of it into another stream.

All code-examples out there use a buffer in form of a byte-array.

Is there a more elegant way to this?

If not, what's the ideal size of the buffer. Which factors make up this value?

like image 708
Thomas Danecker Avatar asked Sep 24 '08 19:09

Thomas Danecker


People also ask

How do I write from one stream to another?

CopyTo(Stream, Int32) Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.

What are the different ways to read data from one stream and write to another?

Among these, you can read the contents of a file using Scanner, BufferedReader and, FileReader classes. In the same way, you can write data into a file using BufferedWriter, FileOutputStream, FileWriter.

Can we read write a stream simultaneously?

This is entirely possible, no problem; but you wouldn't use the same stream, you would use two different ones, and pipe data from the input to the output in a loop.

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.


2 Answers

In .NET 4.0 we finally got a Stream.CopyTo method! Yay!

like image 85
Thomas Danecker Avatar answered Sep 27 '22 20:09

Thomas Danecker


Regarding the ideal buffer size:

"When using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes)."

Any stream-reading process will use Read(char buffer[], int index, count), which is the method this quote refers to.

http://msdn.microsoft.com/en-us/library/9kstw824.aspx (Under "Remarks").

like image 25
core Avatar answered Sep 27 '22 21:09

core