How can I write a hashtable into the file without knowing what is in it ?!
Hashtable DTVector = new Hashtable();
just store this into the file, then read it and create a hashtable again.
How can I write a hashtable into the file without knowing what is in it ?!
Hashtable DTVector = new Hashtable();
just store this into the file, then read it and create a hashtable again.
If you are storing only Doubles in your Hashtable you can use the BinaryFormatter to serialize and deserialize your datastructure.
Hashtable DTVector = new Hashtable();
DTVector.Add("key",12);
DTVector.Add("foo",42.42);
DTVector.Add("bar",42*42);
// write the data to a file
var binformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using(var fs = File.Create("c:\\temp\\vector.bin"))
{
binformatter.Serialize(fs, DTVector);
}
// read the data from the file
Hashtable vectorDeserialized = null;
using(var fs = File.Open("c:\\temp\\vector.bin", FileMode.Open))
{
vectorDeserialized = (Hashtable) binformatter.Deserialize(fs);
}
// show the result
foreach(DictionaryEntry entry in vectorDeserialized)
{
Console.WriteLine("{0}={1}", entry.Key,entry.Value);
}
Keep in mind that the objects you add to your Hashtable need to be serializable. The value types in the .Net framework are and some of the other classes.
If you would have created your own class like this:
public class SomeData
{
public Double Value {get;set;}
}
And you add an instance to the Hashtable like so:
DTVector.Add("key",new SomeData {Value=12});
You'll be greeted with an exception when calling Serialize:
Type 'SomeData' in Assembly 'blah' not marked as serializable.
You can follow the hint stated in the exception message by adding the attribute Serializable to your class
[Serializable]
public class SomeData
{
public Double Value {get;set;}
public override string ToString()
{
return String.Format("Awesome! {0}", Value );
}
}
Ultimately I think to easily be able to write objects out they need to be serializable. You could use something like a dotnet protobuf implementation to store it more efficiently than just a plain dump to a file.