0

i have a class which has a string and a hash table.hash table contains set of key(string) values and bitmap file for each key attribute. how do i serialize this into binary file?

    public void SerializeObject(List<Poem> poems)
    {

        using (Stream stream = File.Open("data.bin", FileMode.Create))
        {
            BinaryFormatter bin = new BinaryFormatter();
            bin.Serialize(stream, poems);
        }
    }

    public List<Poem> DeSerializeObject()
    {
        List<Poem> poems1;
        using (Stream stream = File.Open("data.bin", FileMode.Open))
        {
            BinaryFormatter bin = new BinaryFormatter();

            var lizards2 = (List<Poem>)bin.Deserialize(stream);
            poems1 = (List<Poem>)lizards2;
        }
        return poems1;
    }

//poem class

   [Serializable()]
public class Poem  
{
    string poemName;
    Hashtable poemContent; contains set of keys(strings) , values(bitmap)//

    public Poem() {

        poemContent = new Hashtable();

    }
    public string PoemName
    {
        get { return poemName; }
        set { poemName = value; }
    }

    public Hashtable PoemContent
    {
        get { return poemContent; }
        set { poemContent = value; }
    }}

but this always generates errors.

Hashan
  • 185
  • 2
  • 2
  • 8

1 Answers1

1

I can run your code without error. Calling code:

   SerializeObject(new List<Poem>
                                {
                                    new Poem
                                        {
                                            PoemContent = new Hashtable {{"Tag", new System.Drawing.Bitmap(1, 1)}},
                                            PoemName = "Name"
                                        }
                                });

 var poems2 = DeserializeObject();

What is the error you are seeing? Is it a compiler error or a runtime exception? I can run this code without problem on an example list of poems. By the way, I recommend using Dictionary<K,V> instead of HashTable.

Bart
  • 19,692
  • 7
  • 68
  • 77
Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77
  • Bitmap b = new Bitmap(path); bitmap contains a image data, when i serialize hash table its saying tha bitmap does not impliment a interface iserializable. then i save images into local disk to achive percistence. – Hashan Oct 28 '12 at 04:31
  • Yes, I suspected that the image may have been not serializable (it contains the native image resource). What you want to do is serialize the raw image bytes. You can implement custom serialization logic to write the data (bytes) of the image, instead of the bitmap object. – Anders Forsgren Oct 28 '12 at 10:36