【问题标题】:Read dictionary from dat file从 dat 文件中读取字典
【发布时间】:2014-08-28 09:46:25
【问题描述】:

我将字典写入 dat 文件,我的字典看起来像:

Dictionary<string, Dictionary<string,string>>

现在我的问题是从文件中读取 Dictionary ,我尝试使用 BinaryReader 和 StreamReader 但我的 Dictionary 仍然为空。

我的写代码:

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();

有人知道我能做什么吗?

【问题讨论】:

    标签: c# file dictionary filestream binaryreader


    【解决方案1】:

    首先,您需要执行读取r.read()。然后 - 反序列化读取的结构。

    请注意,将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);
                }
            }
        }
    

    【讨论】:

    • OpenOrCreate 阅读?为什么要创建它?我猜如果将空流传递给Deserialize,它会抛出异常。
    • Frankie 我怎么能这样做,我怎么能反序列化读取的结构? Sriram 是的,你说得对,我解决了这个问题。
    • @Sriram Sakthivel:是的,你是对的。我的错误。应该是 FileMode.Open。我没有提供验证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多