0

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 ?

1 Answers1

3

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);
            }
        }
    }
frankie
  • 728
  • 1
  • 10
  • 28
  • `OpenOrCreate` for reading? Why would you want to create it? It will throw exception I guess if empty stream is passed to `Deserialize`. – Sriram Sakthivel Aug 28 '14 at 09:58
  • Frankie how could I do this , how could I deserialize readed structurd? Sriram yes you right I fixed this . – user2915374 Aug 28 '14 at 10:05
  • @Sriram Sakthivel: yes, you are right. my error. Should be FileMode.Open. I didn't provide validations. – frankie Aug 28 '14 at 10:11