0

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.

rene
  • 41,474
  • 78
  • 114
  • 152
Amir Hossein
  • 249
  • 2
  • 4
  • 14
  • 1
    See the discussion here: http://stackoverflow.com/questions/10615896/serialize-hashtable-using-protocol-buffers-net the author put down a solution. I cannot speak to its quality – Devon Burriss Aug 29 '15 at 07:58
  • Do you know which types will be in it? I don't mean the exact instances, just the possible types on it (classes you own, framework classess...) – Gusman Aug 29 '15 at 08:02
  • @Gusman something like 2D array. – Amir Hossein Aug 29 '15 at 08:10
  • but those will be your types? i'm asking it because if those are known .net types or your own types which you can add the [Serializable] attribute then serializing them is the best way, if yes then I will show you how to serialize it – Gusman Aug 29 '15 at 08:11
  • it's Double Type @Gusman. yes please. – Amir Hossein Aug 29 '15 at 08:14

2 Answers2

6

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 );
    }
}
rene
  • 41,474
  • 78
  • 114
  • 152
0

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.