Search code examples
c#filedictionaryfilestreambinaryreader

Read dictionary from dat file


I wrote Dictionary to dat file , my Dictionary look like:

Dictionary<string, Dictionary<string,string>>

Now my problem is to read from file the Dictionary ,I tried to use BinaryReader and StreamReader but my Dictionary is still null.

My write code:

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

My read code :

FileStream fs = newFileStream(FILE_NAME , FileMode.OpenOrCreate);
streamReader r = new StreamReader(fs);
Dictionary<string, Dictionary<string,string>> main = r.read();

Someone have any idea what can I do ?


Solution

  • Firstly, your need to perform read r.read(). Then - deserialize readed structure.

    Note, that it is good practice to put IDisposable objects into using statement.

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