5

im trying to convert a stream (System.Net.ConnectStream) to a byte array. Any thoughts/examples on how this can be done?

2
  • 3
    Just read it into a buffer (byte[]). Look at Stream.Read on MSDN. Commented Sep 28, 2012 at 19:17
  • @Oded, yes, but it's not a very easy way to copy the whole content of the stream (unless you know its length, which isn't always the case with ConnectStream) Commented Sep 28, 2012 at 19:19

3 Answers 3

14
Stream sourceStream = ... // the ConnectStream
byte[] array;
using (var ms = new MemoryStream())
{
    sourceStream.CopyTo(ms);
    array = ms.ToArray();
}
Sign up to request clarification or add additional context in comments.

2 Comments

In this case you use memory in 3 times more than your stream. It is not so good if your streams can take more memory than your pc have. In this case you need to use Stream.Read to read chunks of data from source stream and work with this chunks.
Note that Stream.CopyTo is only available in .NET 4.0 and up. See Kevin's answer for a pre 4.0 version.
4

Try this...

    private static readonly object _lock = new object();

    public static byte[] readFullStream(Stream st)
    {
        try
        {
            Monitor.Enter(_lock);
            byte[] buffer = new byte[65536];
            Int32 bytesRead;
            MemoryStream ms = new MemoryStream();
            bool finished = false;
            while (!finished)
            {
                bytesRead = st.Read(buffer.Value, 0, buffer.Length);
                if (bytesRead > 0)
                {
                    ms.Write(buffer.Value, 0, bytesRead);
                }
                else
                {
                    finished = true;
                }
            }
            return ms.ToArray();
        }
        finally
        {
            Monitor.Exit(_lock);
        }
    }

2 Comments

Heres a tip, if you are using a rounded number buffer (like 64k in your example), you can replace 65536 with 64 << 10 where the left hand side is your number and on the right hand side 0 = Bytes, 10 = Kilobites, 20 = Megabytes, 30 = Gigabytes, ect... So a 2MB buffer would be 2 << 20
Also, why are you locking on _lock? if you are trying to get exclusive access to the stream you should be locking on something tied to the stream (or call Stream.Synchronized before it gets passed in). You are doing nothing in your code that would break if you converted did two different streams at the same time
0

In one answer from Freeetje there is method writen named 'ReadToEnd'. Worked like a charm for me...

How do I get the filesize from the Microsoft.SharePoint.Client.File object?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.