Write Int array to Stream in .NET

10,401

Solution 1

The simplest option would be to use BinaryWriter wrapping your output stream, and call Write(int) for each of your int values. If that doesn't use the right endianness for you, you could use EndianBinaryWriter from my MiscUtil library.

I don't know of anything built-in to do this more efficiently... I'd hope that the buffering within the stream would take care of it for the most part.

Solution 2

System.Array and System.Int32 both have the SerializableAttribute and so both support default serialization in a retrievable format.

http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx

There is sample code for Binary output and readback here:

http://msdn.microsoft.com/en-us/library/aa904194(VS.71).aspx

Share:
10,401
MartinStettner
Author by

MartinStettner

Self-employed software developer and consultant for software engineering

Updated on June 25, 2022

Comments

  • MartinStettner
    MartinStettner almost 2 years

    what's the best way to write the binary representation of an int array (Int32[]) to a Stream?

    Stream.Write only accepts byte[] as source and I would like to avoid converting/copying the array to an byte[] (array but instead streaming directly from the 'original location').

    In a more system-oriented language (a.k.a. C++) I would simply cast the int array to a byte* but as far as I understood this isn't possible with C# (and moreover, casting byte* to byte[] wouldn't work out either way)

    Thanks

    Martin

    PS: Actually, I would also like to stream single int values. Does using BinaryConverter.GetBytes() create a new byte array? In this case I extend my question to how to efficiently stream single int values ...

  • MartinStettner
    MartinStettner over 13 years
    Thanks, but I since need to control exactly which bytes are written, I'll go with BinaryWriter.
  • Matt
    Matt over 9 years
    In a very unscientific test the buffer seems to handle looping over the array and calling Write(int) on each value efficiently. Thanks.
  • Nyerguds
    Nyerguds about 5 years
    Do be careful; stream wrappers like BinaryWriter tend to close the stream when they're done with it... not handy if you want to pass the stream with its written contents on to something else to handle stuff like writing it.
  • Jon Skeet
    Jon Skeet about 5 years
    @Nyerguds: BinaryWriter provides an option of leaving the stream open for precisely this reason. I haven't included details of that in the answer as the question didn't indicate that it was necessary.
  • Nyerguds
    Nyerguds about 5 years
    I know, I just thought it was worth at least adding as comment because I ran into that issue again today... on an old 3.5 project, too, where that option isn't available. Ah well, dispose-blocking wrapper class it is.