Results 1 to 4 of 4

Thread: [RESOLVED] Serializing to Byte array

  1. #1

    Thread Starter
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Resolved [RESOLVED] Serializing to Byte array

    I'm trying to take a structure, and turn it into an array of Bytes so that I can send it via UDP. It seems like this should be a case of using a BinaryFormatter to serialize the structure, but I can't see any good way of turning this into an array of Bytes. Any suggestions?
    My usual boring signature: Nothing

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Serializing to Byte array

    This is just a wild guess, havent even tested it properly.

    VB.Net Code:
    1. Dim c As New Class1
    2.         Dim formatter As Runtime.Serialization.IFormatter = New Runtime.Serialization.Formatters.Binary.BinaryFormatter
    3.         Dim memStream As New IO.MemoryStream
    4.         formatter.Serialize(memStream, c)
    5.         Using b As New IO.BinaryReader(memStream)
    6.             Dim bte(b.BaseStream.Length) As Byte
    7.             b.Read(bte, 0, b.BaseStream.Length)
    8.         End Using
    9.         memStream.Close()
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3

    Thread Starter
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Serializing to Byte array

    Thanks, it looks quite plausible, I'll look it up. The MemoryStream was the step I was missing. I got thinking about it as I was driving around today, and realized I should pursue something close to that (a filestream), but I had forgotten the MemoryStream (that's ironic), which seems more likely.
    My usual boring signature: Nothing

  4. #4

    Thread Starter
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Serializing to Byte array

    Finally got to test this, and it worked well. Oddly, BaseStream.Length returns a Long (ok, I guess that's not really all that odd, but it IS a huge number), so it had to be cast to an integer (it will never be that big in this app).
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width