0

I have a binary file that holds a Dictionary object. I can access the data with the following code.

var result = new Dictionary<string, string>();
        using (FileStream fs1 = File.OpenRead("C:\\MyDictionary.bin"))
        {
            using (BinaryReader br = new BinaryReader(fs1))
            {
                int count = br.ReadInt32();
                for (int i = 0; i < count; i++)
                {
                    string key = br.ReadString();
                    string value = br.ReadString();
                    result[key] = value;
                }
            }
        }

I would prefer to include this binary file within my application and not refer to an external file at run time. How do I do the same thing from an embedded binary file?

I found the following code in another thread but am struggling to understand how I can get it to work with the above data.

var assembly = Assembly.GetExecutingAssembly();
        var resourceName = "MyProgram.Resources.MyDictionary.bin";

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        using (StreamReader reader = new StreamReader(stream))
        {
            string result = reader.ReadToEnd();
        }
Lundin
  • 195,001
  • 40
  • 254
  • 396
James
  • 87
  • 1
  • 9
  • 1
    Duplicate of [How to read embedded resource text file](https://stackoverflow.com/questions/3314140/how-to-read-embedded-resource-text-file) – Herohtar Feb 17 '20 at 09:18
  • 1
    Once you have the resource stream, use your `BinaryReader` and everything else as usual. `StreamReader` is for text only. – Herohtar Feb 17 '20 at 09:19
  • @Herohtar Thanks for your help. I should have seen that. All good now – James Feb 17 '20 at 10:52

1 Answers1

0

You can use the following code:

var result = new Dictionary<string, string>();
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyProgram.Resources.MyDictionary.bin";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (BinaryReader reader = new BinaryReader(stream))
  {
    int count = reader.ReadInt32();
    for (int i = 0; i < count; i++)
      {
        string key = reader.ReadString();
        string value = reader.ReadString();
        result[key] = value;
      }
  }
SUMIT PATRO
  • 166
  • 5