Reputation: 439
I am having trouble writing to stream. I think i understand why, but im not really following how to get around the issue. Please see example code below
The requirement that the caller of Writer in the example below manages the stream, not the Writer.
this is example code in the caller:
using (Stream stream1 = new MemoryStream())
using (Stream stream2 = new FileStream("ex.txt", FileMode.Create))
{
//example 1:
Writer writer1 = new Writer();
writer1.WriteToStream(stream1);
//example 2:
Writer writer2 = new Writer();
writer2.WriteToStream(stream2);
}
This is the Writer
class: its supposed to leave stream open after its done with it.
public class Writer
{
public void WriteToStream(Stream destination)
{
Write(destination, "abc");
}
private void Write(Stream destination, string data)
{
Streamwriter sw = new StreamWriter(destination);
sw.Write(data);
}
}
in this setup, nothing shows up in MemoryStream
or "ex.txt"
. I am guessing its because once you exit the Write
method, StreamWriter
is out of context, and stream goes with it before it gets a chance to be written to a file.
If I change the Write
method to the example below, then i can get something to show up in the file, but the stream ends up closed, which goes against the requirement:
private void Write(Stream destination, string data)
{
using(Streamwriter sw = new StreamWriter(destination))
{
sw.Write(data);
}
}
So, how do I write a string to a stream (Memory of File), without closing the stream in the process. thank you
Upvotes: 1
Views: 2049
Reputation: 181077
The easiest way is probably to use the StreamWriter constructor that allows us to leave the underlying Stream open and set leaveOpen
to true.
private void Write(Stream destination, string data)
{
using (var sw = new StreamWriter(destination, Encoding.UTF8, 1024, leaveOpen: true))
{
sw.Write(data);
}
}
Upvotes: 0
Reputation: 1937
You are missing Stream Flush.
Following will solve the issue:
private void Write(Stream destination, string data)
{
var sw = new StreamWriter(destination);
sw.Write(data);
sw.Flush();
}
However, open streams are notorious.
Upvotes: 1