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

时间:2010-11-11 13:28:07

标签: c# .net resources

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

以下代码段有什么问题?

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

stream总是= null!

2 个答案:

答案 0 :(得分:7)

        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");

答案 1 :(得分:1)

<ResourceNamespace>.ResourceManager.GetString(<textresourcename>);