简体   繁体   English

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

[英]C#: Reading the content of a file, which is embedded in a resource file

How can I read a text file , which is embedded in a resx file with the help of the ResourceManager class? 如何在ResourceManager类的帮助下读取嵌入在resx文件中文本文件

Whats wrong with the following snippet? 以下代码段有什么问题?

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

stream is alway = null! 流是alway = 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));
            }
        }

The resource name is determined by namespace and filename. 资源名称由名称空间和文件名确定。 Say file MyTxt.txt exists in the root of the project, which has default namespace MyNs then the resource name will be: MyNs.MyTxt.txt 假设文件MyTxt.txt存在于项目的根目录中,其默认名称空间为MyNs则资源名称为: MyNs.MyTxt.txt

EDIT 编辑

I should learn to read the question. 我应该学习阅读这个问题。 I haven't tested but this should give you what you want: 我没有测试,但这应该给你你想要的:

    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");
<ResourceNamespace>.ResourceManager.GetString(<textresourcename>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM