CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Nov 2008
    Posts
    18

    Converting an object to a byte stream

    I'm trying to convert an object to a byte stream and I'm using the code below to do it

    Code:
    public static byte[] ObjectToByteArray(System.Object obj)
        {
            MemoryStream fs = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, obj);
                return fs.ToArray();
            }
            catch (Exception e)
            {
    			Debug.Log("Exception sending friend request: " + e.Message);
                return null;
            }
            finally
            {
                fs.Close();
            }
        }
    The problem is that this puts a large C# header on the front of the byte stream. Is there a way to determine the size of the header, so when I send the stream over a socket, I can skip sending the header? Or better yet, not generate the header at all?

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Converting an object to a byte stream

    Does the FormatterType property help?

    http://msdn.microsoft.com/en-us/libr...typestyle.aspx

  3. #3
    Join Date
    Nov 2008
    Posts
    18

    Re: Converting an object to a byte stream

    I'm not sure how I'd use that, but after a little more searching, I found another approach using Marshal.

    Code:
    public static byte[] ObjectToByteArray(System.Object obj)
        {
    		int size = Marshal.SizeOf(obj);
    	    byte[] arr = new byte[size];
    	    IntPtr ptr = Marshal.AllocHGlobal(size);
    	
    	    Marshal.StructureToPtr(obj, ptr, true);
    	    Marshal.Copy(ptr, arr, 0, size);
    	    Marshal.FreeHGlobal(ptr);
    	
    	    return arr;
    }
    This required me to add some tags to the class, but it worked.

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

Featured