Search code examples
c#embedded-resource

Loading resources from external dll, and determining the resource type


I have a C# app with all our resources in a single library. This is basically several folders, each having one or more .resx files in it.

For the most part, the .resx files have string resources. A few have file resources.

I have a task to go through these string resources and do something with them. Just the string ones though, not the files.

Currently, I can load the resources from a separate dll:

var asm = System.Reflection.Assembly.LoadFrom("External.Resources.dll");

string[] strings = asm.GetManifestResourceNames();

foreach (var s in strings)
{
    var rm = new ResourceManager(s, asm);

    var rs = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true);

    foreach (DictionaryEntry de in rs)
    {
        var val = de.Value.ToString();
        var key = de.Key.ToString();
    }
}

Unfortunately there's no way for me to tell what the resource is. If it's a file, the Value will just contain the text of that file.

How can I check if the value is a string or a file (text) coming from the resource file?


Solution

  • If you want to get the original Type of resource, then you will have to access the original resource object. It will have static properties of the specific types; e.g. files will be byte[], strings as string etc.

    var asm = System.Reflection.Assembly.LoadFrom("External.Resources.dll");
    string[] strings = asm.GetManifestResourceNames();
    
    foreach (var s in strings)
    {
        var rm = new ResourceManager(s, asm);
    
        // Get the fully qualified resource type name
        // Resources are suffixed with .resource
        var rst = s.Substring(0, s.IndexOf(".resource"));
        var type = asm.GetType(rst, false);
    
        // if type is null then its not .resx resource
        if (null != type)
        {
            var resources = type.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
            foreach (var res in resources)
            {
                // collect string type resources
                if (res.PropertyType == typeof(string))
                {
                    // get value from static property
                    string myResourceString = res.GetValue(null, null) as string;
                }
            }
        }
    
    }