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(); } 
3
  • 1
    Duplicate of How to read embedded resource text file Commented Feb 17, 2020 at 9:18
  • 1
    Once you have the resource stream, use your BinaryReader and everything else as usual. StreamReader is for text only. Commented Feb 17, 2020 at 9:19
  • @Herohtar Thanks for your help. I should have seen that. All good now Commented Feb 17, 2020 at 10:52

1 Answer 1

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; } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.