Search code examples
c#.net.net-assemblyembedded-resource

Iterating through string resources in another assembly


I would like to iterate through all string resources in a given .NET assembly. To do so I came up with the following code:

public void IterateResourcesInAssembly(string filename)
{
  var assembly = Assembly.LoadFile(filename);
  string[] resourceNames = assembly.GetManifestResourceNames();

  foreach (var resourceName in resourceNames)
  {
    var resourceManager = new ResourceManager(resourceName, assembly);
    var resourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);
    // Exception is thrown!
  }
}

The problem here is, that GetResourceSet always throws an exception:

Missing ManifestResourceException For the given culture or the neutral culture no resources could be found...

But I'm pretty sure that's not true. The assembly contains lots of resources in English and German. When opening the Assembly with the .NET-Reflector, I can see those resources, too.


Solution

  • GetManifestResourceNames() method returns resource name with the extension. Before create resource manager instance, you have to remove the extension from resource name and pass only the resource base name.

    public void IterateResourcesInAssembly(string filename)
            {
                var assembly = Assembly.LoadFile(filename);
                string[] resourceNames = assembly.GetManifestResourceNames();
    
                foreach (var resourceName in resourceNames)
                {
                    string baseName = Path.GetFileNameWithoutExtension(resourceName);
                    ResourceManager resourceManager = new ResourceManager(baseName, assembly);
    
                    var resourceSet = resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);
                    // Exception is thrown!
                }
            }