我将Dictionary写入dat文件,我的词典看起来像:
Dictionary<string, Dictionary<string,string>>
现在我的问题是从文件中读取字典,我试图使用BinaryReader和StreamReader但我的字典仍然是空的。
我的写代码:
static void WriteToFile(Dictionary<string, Dictionary<string, string>> dic)
FileStream fs = new FileStream(FILE_NAME, FileMode.OpenOrCreate);
StreamWriter w = new StreamWriter(fs);
BinaryFormatter bw = new BinaryFormatter();
bw.Serialize(fs,dic);
w.Write(dic);
我的阅读代码:
FileStream fs = newFileStream(FILE_NAME , FileMode.OpenOrCreate);
streamReader r = new StreamReader(fs);
Dictionary<string, Dictionary<string,string>> main = r.read();
有人知道我该怎么办?
答案 0 :(得分:2)
首先,您需要执行阅读r.read()
。然后 - 反序列化readed结构。
请注意,最好将IDisposable
个对象放入using
语句中。
static Dictionary<string, Dictionary<string, string>> ReadFromFile()
{
using (var fs = new FileStream("C:/test.dat", FileMode.Open))
{
var bw = new BinaryFormatter();
return (Dictionary<string, Dictionary<string, string>>)bw.Deserialize(fs);
}
}
static void WriteToFile(Dictionary<string, Dictionary<string, string>> dic)
{
using (var fs= new FileStream("C:/test.dat", FileMode.OpenOrCreate))
{
using (var w = new StreamWriter(fs))
{
var bw = new BinaryFormatter();
bw.Serialize(fs, dic);
w.Write(dic);
}
}
}