如何将Hashtable写入文件?

Ami*_*ein 0 c# hashtable file

如何在不知道文件内容的情况下将哈希表写入文件?

Hashtable DTVector = new Hashtable();
Run Code Online (Sandbox Code Playgroud)

只需将其存储到文件中,然后读取它并再次创建一个哈希表.

ren*_*ene 5

如果你在你的Hashtable中只存储双打可以使用的BinaryFormatter序列化和反序列化的数据结构.

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);
}
Run Code Online (Sandbox Code Playgroud)

请记住,添加到Hashtable的对象需要可序列化..Net框架中的值类型和一些其他类.

如果您要创建自己的类,如下所示:

public class SomeData
{
    public Double Value {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样在Hashtable中添加一个实例:

DTVector.Add("key",new SomeData {Value=12});
Run Code Online (Sandbox Code Playgroud)

调用Serialize时会遇到异常:

在Assembly'blah'中键入'SomeData'未标记为可序列化.

您可以通过向类中添加Serializable属性来遵循异常消息中所述的提示

[Serializable]
public class SomeData
{
    public Double Value {get;set;}
    public override string ToString()
    {
       return String.Format("Awesome! {0}", Value );
    }
}
Run Code Online (Sandbox Code Playgroud)