开发者

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

开发者 https://www.devze.com 2023-01-24 19:35 出处:网络
How can I read a text file, which is embedded in a resx file with the help of the ResourceManager class?

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 strea开发者_Python百科m = 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>);
0

精彩评论

暂无评论...
验证码 换一张
取 消