connecting streams ...

  • Thread starter Thread starter bonk
  • Start date Start date
B

bonk

Hello

how do I connect streams in c# ?

Imagine the followung scenario: I have a StreamWriter that writes Text to a
Stream. How can I tell that Stream to pass that Data to another Stream
(connect it to another output Stream) ? In java I am used to connect
streams to each other via thier Constructors.
For example:
new BufferedWriter(new OutputStreamWriter(new FileOutputStream("soc.txt"),
"UTF-8"));

Or even more interesting: What if I wanted that Stream to pass its Data to
multiple other Streams. What do I have to do in that case ?

<> heh, didn't you ever watch Ghostbusters?
<> you can't cross the streams

.... does that mean ... ?
 
bonk said:
how do I connect streams in c# ?

Imagine the followung scenario: I have a StreamWriter that writes Text to a
Stream. How can I tell that Stream to pass that Data to another Stream
(connect it to another output Stream) ? In java I am used to connect
streams to each other via thier Constructors.
For example:
new BufferedWriter(new OutputStreamWriter(new FileOutputStream("soc.txt"),
"UTF-8"));

In this case, you'd just use new StreamWriter (new FileStream(...)).
There's no need for a BufferedWriter particularly, although you could
always use BufferedStream in there (between the StreamWriter and the
FileStream) if you want.
Or even more interesting: What if I wanted that Stream to pass its Data to
multiple other Streams. What do I have to do in that case ?

I don't believe there's a stream class which writes to multiple
streams, but it wouldn't be particularly hard to write one - just have
a collection of streams, and any time data is written to the single
stream, write it to all the others.
 
how do I connect streams in c# ?
(connect it to another output Stream) ? In java I am used to connect
streams to each other via thier Constructors.
For example:
new BufferedWriter(new OutputStreamWriter(new FileOutputStream("soc.txt"),
"UTF-8"));

Example of connecting multiple streams. In this case, I don't think the
buffered stream or the fs provide much value as you could just use the sr
only and save indirection to two other streams. If one was a zip stream or
crypto stream, then value is apparent.

using(FileStream fs = new FileStream(@"c:\myfile.txt", FileMode.Open))
using(BufferedStream bs = new BufferedStream(fs))
using(StreamReader sr = new StreamReader(bs))
{
string line = null;
while((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Or even more interesting: What if I wanted that Stream to pass its Data to
multiple other Streams. What do I have to do in that case ?

Create your own stream by inheritence of stream. Then allow your stream to
Add stream instances to it of the type you can write to. Then override
write method to write to all streams in your collection.
 
Back
Top