C#:读取嵌入在资源文件中的文件内容

标签 c# .net resources

如何在 ResourceManager 类的帮助下读取嵌入在 resx 文件 中的文本文件

以下代码片段有什么问题?

ResourceManager resman = new ResourceManager("Mynamespace.RESXFileName", Assembly.GetExecutingAssembly());
Stream stream = resman2.GetStream("ResourceName");

流总是 = null!

最佳答案

        using (var resourceStream = Assembly.GetExecutingAssembly()
                    .GetManifestResourceStream(resourceName))
        {
            if (resourceStream != null)
            {
                using (var textStreamReader = new StreamReader(resourceStream))
                {
                    text = textStreamReader.ReadToEnd();
                }
            }
            else
            {
                throw (new MissingManifestResourceException(resourceName));
            }
        }

资源名称由命名空间和文件名决定。假设文件 MyTxt.txt 存在于项目的根目录中,它具有默认命名空间 MyNs 那么资源名称将是:MyNs.MyTxt.txt

编辑

我应该学会阅读问题。我还没有测试过,但这应该会给你你想要的:

    static object GetResxObject(string resxPathName, string resourceKey)
    {
        using (var resxReader = new ResXResourceReader(resxPathName))
        {
            return resxReader
                .Cast<DictionaryEntry>()
                .Single(d => string.Equals(d.Key,
                                           resourceKey))
                .Value;
        }
    }

    ...
    var myString=(string)GetResxObject(@"path\to\resx.resx","myStringKey");

关于C#:读取嵌入在资源文件中的文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4154872/

相关文章:

maven - 如何将 Maven 项目配置为不期望 Eclipse 中的资源目录

c# - 函数的复杂性和算法

c# - 为什么要从 Unity 委托(delegate)事件中删除事件?

c# - 无法在托管代码中捕获 native 异常

c# - ResourceManager - 如何找到嵌入式资源文件所需的基本名称?

visual-c++ - 在不同嵌套级别的多个项目中包含公共(public)资源(Visual C++)

c# - 暴力破解函数输入以找到最大值的算法

c# - 通过协程调用方法给出 NullReferenceException

c# - 为什么我的 hello world with streams 不显示任何内容?

c# - .NET 正则表达式空白特殊字符