Martin
Martin

Reputation: 40573

How to stream an XElement/XDocument with WCF?

I have the following method signature. I cannot change it (i.e. I cannot change the return type).

public Stream GetMusicInfo(string songId)
{
    XElement data = dao.GetMusicInfo(songId);

    // how do I stream the XElement?
}

How can I stream the XElement/XDocument with WCF?

Upvotes: 2

Views: 1543

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500475

That's reasonably simple, if you don't mind actually fetching all the data in that first line:

public Stream GetMusicInfo(string songId)
{
    XElement data = dao.GetMusicInfo(songId);
    MemoryStream ms = new MemoryStream();
    data.Save(ms);
    ms.Position = 0;
    return ms;
}

In other words, just write it out in-memory, and return a stream over that in-memory representation. Note the Position = 0; call, which is necessary as otherwise the stream will be positioned at the end of the data.

I would hope that WCF would then just do the right thing with the stream.

Upvotes: 5

Related Questions