Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Objects to bytes...

Objects to bytes...

Scheduled Pinned Locked Moved C#
questiondata-structurestutorial
9 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    Niklas Ulvinge
    wrote on last edited by
    #1

    How do I convert an array of objects to an array of bytes? I don't know how to do it the old way like in C, get the address of and the size of the object and then save it to a file... Niklas Ulvinge aka IDK

    T 1 Reply Last reply
    0
    • N Niklas Ulvinge

      How do I convert an array of objects to an array of bytes? I don't know how to do it the old way like in C, get the address of and the size of the object and then save it to a file... Niklas Ulvinge aka IDK

      T Offline
      T Offline
      turbochimp
      wrote on last edited by
      #2

      If you're just wanting to serialize the array, the following should work (generically, for any binary serializable type): using System; using System.Runtime.Serialization.Formatters.Binary; namespace SomeStuff { class Class1 { [STAThread] static void Main(string[] args) { string[] foo = new string[3]{"a", "b", "c"}; byte[] bytes = BinaryConverter.SerializeThis(foo); string[] newFoo = (string[])BinaryConverter.DeserializeThat(bytes); foreach(string s in newFoo) Console.WriteLine(s); Console.ReadLine(); } } class BinaryConverter { private BinaryConverter(){} public static object DeserializeThat(byte[] bytes) { object graph = null; if (bytes != null && bytes.Length > 0) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(bytes); graph = formatter.Deserialize(stream); stream.Close(); } return graph; } public static byte[] SerializeThis(object graph) { byte[] bytes = null; if (graph != null) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, graph); bytes = stream.GetBuffer(); stream.Close(); } return bytes; } } }

      The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

      N 1 Reply Last reply
      0
      • T turbochimp

        If you're just wanting to serialize the array, the following should work (generically, for any binary serializable type): using System; using System.Runtime.Serialization.Formatters.Binary; namespace SomeStuff { class Class1 { [STAThread] static void Main(string[] args) { string[] foo = new string[3]{"a", "b", "c"}; byte[] bytes = BinaryConverter.SerializeThis(foo); string[] newFoo = (string[])BinaryConverter.DeserializeThat(bytes); foreach(string s in newFoo) Console.WriteLine(s); Console.ReadLine(); } } class BinaryConverter { private BinaryConverter(){} public static object DeserializeThat(byte[] bytes) { object graph = null; if (bytes != null && bytes.Length > 0) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(bytes); graph = formatter.Deserialize(stream); stream.Close(); } return graph; } public static byte[] SerializeThis(object graph) { byte[] bytes = null; if (graph != null) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, graph); bytes = stream.GetBuffer(); stream.Close(); } return bytes; } } }

        The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

        N Offline
        N Offline
        Niklas Ulvinge
        wrote on last edited by
        #3

        I don't know what to serilize an array is but you forget to include using System.IO; And I got some errors wich I fixed with making the class I used [Serializable] I really just want to save the data to a file... And after a little fixing it worked. Thanks Niklas Ulvinge aka IDK

        N T 2 Replies Last reply
        0
        • N Niklas Ulvinge

          I don't know what to serilize an array is but you forget to include using System.IO; And I got some errors wich I fixed with making the class I used [Serializable] I really just want to save the data to a file... And after a little fixing it worked. Thanks Niklas Ulvinge aka IDK

          N Offline
          N Offline
          Niklas Ulvinge
          wrote on last edited by
          #4

          I got an error. If I saved an array of 8 objects it loads 9 and the last one is null. That's bad. Niklas Ulvinge aka IDK

          T 1 Reply Last reply
          0
          • N Niklas Ulvinge

            I don't know what to serilize an array is but you forget to include using System.IO; And I got some errors wich I fixed with making the class I used [Serializable] I really just want to save the data to a file... And after a little fixing it worked. Thanks Niklas Ulvinge aka IDK

            T Offline
            T Offline
            turbochimp
            wrote on last edited by
            #5

            I wasn't really aiming at providing you with a completed application - just some sample code. If you don't know what serialization is, I would suggest reading about it before using it - it's in the MSDN documentation under "Serialization". Glad to have helped.

            The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

            1 Reply Last reply
            0
            • N Niklas Ulvinge

              I got an error. If I saved an array of 8 objects it loads 9 and the last one is null. That's bad. Niklas Ulvinge aka IDK

              T Offline
              T Offline
              turbochimp
              wrote on last edited by
              #6

              That's not a lot to go on. I have no idea what your source code looks like. If you'd like to include it (code that builds the array, serializes it and deserializes it, along with the type you're trying to serialize in the array), I can have a look.

              The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

              N 1 Reply Last reply
              0
              • T turbochimp

                That's not a lot to go on. I have no idea what your source code looks like. If you'd like to include it (code that builds the array, serializes it and deserializes it, along with the type you're trying to serialize in the array), I can have a look.

                The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

                N Offline
                N Offline
                Niklas Ulvinge
                wrote on last edited by
                #7

                It's huge... I'll only post some parts of it... The code for each class is huge, I hope the structure is enough Item.cs: namespace NiklasUlvinge.ChipsEater { [Serializable] abstract class Item [Serializable] class Void : Item [Serializable] class Cord : Item [Serializable] class Ground : Item [Serializable] class theGround : Item ... } form1.cs: namespace NiklasUlvinge.ChipsEater { public partial class Form1 : Form { #region FileHandling private void OpenFile_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(this); FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.None); byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); items = (Item[])BinaryConverter.DeserializeThat(data); fs.Flush(); fs.Close(); SetParent(); PB.Refresh(); } private void SaveFile_Click(object sender, EventArgs e) { saveFileDialog1.ShowDialog(this); FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.None); byte[] data = BinaryConverter.SerializeThis(items); fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); } #endregion private void toolStripButtonClear_Click(object sender, EventArgs e) { items = new Item[1] { new theGround(items) }; SetParent(); PB.Refresh(); } private void addItem(Item item) { Item[] titem = new Item[items.Length + 1]; for (int i = 0; i < items.Length; i++) { titem[i] = items[i]; } titem[items.Length] = item; items = titem; SetParent(); if (item.x - PB.Width > hScrollBar1.Maximum) hScrollBar1.Maximum = item.x - PB.Width; if (item.y - PB.Height > vScrollBar1.Maximum) vScrollBar1.Maximum = item.y - PB.Height; } private Item getItem(int x, int y) { for (int i = 0; i < items.Length; i++) { if (Math.Abs(items[i].x - x) < items[i].Width) if (Math.Abs(items[i].y - y) < items[i

                T 1 Reply Last reply
                0
                • N Niklas Ulvinge

                  It's huge... I'll only post some parts of it... The code for each class is huge, I hope the structure is enough Item.cs: namespace NiklasUlvinge.ChipsEater { [Serializable] abstract class Item [Serializable] class Void : Item [Serializable] class Cord : Item [Serializable] class Ground : Item [Serializable] class theGround : Item ... } form1.cs: namespace NiklasUlvinge.ChipsEater { public partial class Form1 : Form { #region FileHandling private void OpenFile_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(this); FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.None); byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); items = (Item[])BinaryConverter.DeserializeThat(data); fs.Flush(); fs.Close(); SetParent(); PB.Refresh(); } private void SaveFile_Click(object sender, EventArgs e) { saveFileDialog1.ShowDialog(this); FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.None); byte[] data = BinaryConverter.SerializeThis(items); fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); } #endregion private void toolStripButtonClear_Click(object sender, EventArgs e) { items = new Item[1] { new theGround(items) }; SetParent(); PB.Refresh(); } private void addItem(Item item) { Item[] titem = new Item[items.Length + 1]; for (int i = 0; i < items.Length; i++) { titem[i] = items[i]; } titem[items.Length] = item; items = titem; SetParent(); if (item.x - PB.Width > hScrollBar1.Maximum) hScrollBar1.Maximum = item.x - PB.Width; if (item.y - PB.Height > vScrollBar1.Maximum) vScrollBar1.Maximum = item.y - PB.Height; } private Item getItem(int x, int y) { for (int i = 0; i < items.Length; i++) { if (Math.Abs(items[i].x - x) < items[i].Width) if (Math.Abs(items[i].y - y) < items[i

                  T Offline
                  T Offline
                  turbochimp
                  wrote on last edited by
                  #8

                  I can't really tell for sure, but my guess would be that in your addItem method you're creating an array where the last item (set to the value of the 'item' parameter) is null. Have you inserted a breakpoint in your code just prior to serialization (in SaveFile_Click) to inspect your array and ensure that the length is what you expect it to be, and that all the elements in the array are non-null? If you want, just email the source to me.

                  The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

                  -- modified at 12:42 Saturday 17th September, 2005

                  N 1 Reply Last reply
                  0
                  • T turbochimp

                    I can't really tell for sure, but my guess would be that in your addItem method you're creating an array where the last item (set to the value of the 'item' parameter) is null. Have you inserted a breakpoint in your code just prior to serialization (in SaveFile_Click) to inspect your array and ensure that the length is what you expect it to be, and that all the elements in the array are non-null? If you want, just email the source to me.

                    The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’

                    -- modified at 12:42 Saturday 17th September, 2005

                    N Offline
                    N Offline
                    Niklas Ulvinge
                    wrote on last edited by
                    #9

                    I couldn't find any error in the any of the file funcs... I then made some UI improvements and now the error is gone! Thank you for your help. It's a circuit simulator, but it's not that good yet. It got some foults... It's the Kirchkorvs (or whatever he's called, I can't remember) rule that's not working as it should. turbochimp wrote: The most exciting phrase to hear in science, the one that heralds the most discoveries, is not 'Eureka!' ('I found it!') but 'That's funny...’ That's funny... Niklas Ulvinge aka IDK

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups