简体   繁体   中英

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?

Whats wrong with the following snippet?

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

stream is 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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