Embedded resources in assembly containing culture name in filename will not load

一笑奈何 提交于 2019-12-04 05:58:44

I hope I am not late with answer.

When you add templatename.nl-NL.cshtml as embedded resource, it lands in satellite assembly with resources for nl-NL language.

If you go to bin/debug directory, you'll find nl-NL folder with NAMESPACE.resources.dll in it.

If you decompile this assembly, you'll find templatename.cshtml file inside.

To read it, you have to get this assembly and read resource from it.

To get it, you have to execute this code:

var mainAssembly = AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "ConsoleApp2");

ConsoleApp2 was namespace where I had all my resources. Code above will get assembly only if it is already loaded. I assumed it is.

Then you have to get satellite assembly. This is main difference between standard file reading from embedded resource:

var satelliteAssembly = mainAssembly.GetSatelliteAssembly(CultureInfo.CreateSpecificCulture("nl-NL"));

And then we have standard method to read resource file:

var resourceName = "ConsoleApp2.templatename.cshtml";

using (Stream stream = satelliteAssembly.GetManifestResourceStream(resourceName))
    using (StreamReader reader = new StreamReader(stream))
    {
        string result = reader.ReadToEnd(); // nl-NL template
    }

Example project file here.

Are you sure you have the right name for the ResourceSet when you open the ResourceStream? Unless ManifestResources is your project base namespace and the .cshtml file lives in the root folder that resourceset name is probably invalid.

The way .NET projects generate resourceSet name you use to open the resource stream is based on base namespace plus the folder hierarchy. For Example:

baseNamespaceOfProject.Views.Controller.YourPage.nl-NL.cshtml

The easiest way to check make sure you can see what the resource looks like is to open the final assembly (or resource assembly) with a tool like Reflector/DotPeek and see what the actual embedded resourceSet and Resource Ids are.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!