【问题标题】:Read an embedded binary resource [duplicate]读取嵌入式二进制资源[重复]
【发布时间】:2020-06-01 04:33:52
【问题描述】:

我有一个包含 Dictionary 对象的二进制文件。我可以使用以下代码访问数据。

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

我希望在我的应用程序中包含这个二进制文件,而不是在运行时引用外部文件。如何从嵌入的二进制文件做同样的事情?

我在另一个线程中找到了以下代码,但我很难理解如何让它与上述数据一起工作。

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

【问题讨论】:

  • 获得资源流后,像往常一样使用BinaryReader 和其他一切。 StreamReader 仅用于文本。
  • @Herohtar 感谢您的帮助。我应该看到的。现在一切都好

标签: c# dictionary binary resources


【解决方案1】:

您可以使用以下代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2014-10-17
    • 2019-03-28
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多