serialize list contain hash table
-
14-07-2021 - |
Question
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.
Solution
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
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow