Jonathan Wood
Jonathan Wood

Reputation: 67345

Capture Stream Output to String

I'm calling a library method that writes to a stream. But I want to write to a string. Is this possible? (I do not control the source code of the method I'm calling and so changing that is not an option.)

Experimenting, I tried something like this:

iCalendarSerializer serializer = new iCalendarSerializer();
MemoryStream stream = new MemoryStream();
serializer.Serialize(new iCalendar(), stream, System.Text.Encoding.UTF8);
byte[] buff = new byte[stream.Length];
stream.Read(buff, 0, (int)stream.Length);

But I get an error on the last line that's something about not being able to access a closed stream. Apparently, the Serialize() method closes the stream when it's done.

Are there other options?

Upvotes: 3

Views: 4132

Answers (3)

Alexei Levenkov
Alexei Levenkov

Reputation: 100630

ToArray is one of 2 correct way of getting the data out of memory stream (the other one is GetBuffer and Length). It looks like you just want byte array sized to data of the stream and ToArray does exactly that.

Note that it is by design safe to call these 3 methods on disposed stream, so you can safely wrap using(stream) around the code that write some data to the stream.

In you case stream look to be disposed by serialization code (.Serialize).

iCalendarSerializer serializer = new iCalendarSerializer();
MemoryStream stream = new MemoryStream();
using(stream)
{
  serializer.Serialize(new iCalendar(), stream, System.Text.Encoding.UTF8);
}
byte[] buff = stream.ToArray();

Upvotes: 1

Mike Park
Mike Park

Reputation: 10941

How about byte[] buff = stream.ToArray()?

Upvotes: 2

Raman Zhylich
Raman Zhylich

Reputation: 3697

In your example you need to change the position of the stream before read takes place:

stream.Position = 0;
stream.Read(buff, 0, (int)stream.Length);

In order to write stream to string you can use StreamReader.ReadToEnd() method:

var reader = new StreamReader(stream);
var text = reader.ReadToEnd();

Upvotes: 0

Related Questions