It really depends on whether or not you can trust s.Length
. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
With .NET 4 and above, I'd use Stream.CopyTo
, which is basically equivalent to the loop in my code - create the MemoryStream
, call stream.CopyTo(ms)
and then return ms.ToArray()
. Job done.
I should perhaps explain why my answer is longer than the others. Stream.Read
doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. BinaryReader.Read
will keep going until the end of the stream or your specified size, but you still have to know the size to start with.
The above method will keep reading (and copying into a MemoryStream
) until it runs out of data. It then asks the MemoryStream
to return a copy of the data in an array. If you know the size to start with - or think you know the size, without being sure - you can construct the MemoryStream
to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by MemoryStream.GetBuffer
) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.
See this article for more info (and an alternative implementation).
I have .NET 3.5 SP1 installed on a server with some existing .NET 1.1 applications and haven't noticed any problems whatsoever. The framework versions are completely distinct with respect to 1.1 and 3.5, though I understand that 3.5 includes some patches to 2.0 that might change behavior for 2.0 apps. I haven't noticed anything there either.
You might be interested in this blog post that covers a lot of ground with regards to updating, but specifically mentions that leaving 1.1 apps alone is ok. It also has a lot of references to other sources.
Best Answer
.NET 3.5 adds a lot of new assemblies, but the core runtime is still 2.0. Or actually it is 2.0 SP1, so in very rare cases you may see differences, but in most cases you shouldn't have to do anything.
There's a useful overview of the versions on wikipedia.