Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transfer MemoryStream via WCF Streaming

I am planning to pass MemoryStream via WCF Streaming but it seems not working but when I slightly change the code to pass FileStream instead, it is working. In fact, my purpose is to pass large collection of business objects (serializable). I am using basicHttpBinding. Your suggestion would be much appreciated!

Edited: The symptoms of the issue is that the incoming stream is empty. There is neither error nor exception.

like image 529
Thurein Avatar asked Sep 22 '11 01:09

Thurein


1 Answers

You're not providing many details, however, I'm almost certain I know what the issue is as I've seen that happening a lot.

If you write something to a MemoryStream in order to return that one as the result of a WCF service operation, you need to manually reset the stream to its beginning before returning it. WCF will only read the stream from it current position, hence will return an empty stream if that position hasn't been reset.

That would at least explain the problem you're describing. Hope this helps.

Here some sample code:

    [OperationContract]
    public Stream GetSomeData()
    {
        var stream = new MemoryStream();
        using(var file = File.OpenRead("path"))
        {
            // write something to the stream:
            file.CopyTo(stream);         
            // here, the MemoryStream is positioned at its end
        }
        // This is the crucial part:
        stream.Position = 0L;
        return stream;
    }
like image 111
mthierba Avatar answered Sep 19 '22 06:09

mthierba