程序集中包含区域性名称的程序集中的嵌入式资源将不会加载 [英] Embedded resources in assembly containing culture name in filename will not load

查看:76
本文介绍了程序集中包含区域性名称的程序集中的嵌入式资源将不会加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在类库中嵌入一些电子邮件模板.在我使用包含具有以下表示法的文化名称的文件名之前,该方法可以正常工作:templatename.nl-NL.cshtml 该资源似乎不可用.

I'm trying to embed some email templates in a class library. This works fine, until I use a filename containing a culture-name with the following notation: templatename.nl-NL.cshtml The resource does not seem to be available.

示例代码:

namespace ManifestResources
 {
    class Program
    {
        static void Main(string[] args)
        {
            var assembly = Assembly.GetExecutingAssembly();

            // Works fine
            var mailTemplate = assembly.GetManifestResourceStream("ManifestResources.mailtemplate.cshtml");

            // Not ok, localized mail template is null
            var localizedMailTemplate = assembly.GetManifestResourceStream("ManifestResources.mailtemplate.nl-NL.cshtml");
        }
    }
}

模板均将构建操作设置为"EmbeddedResource".

Templates both have build action set to 'EmbeddedResource'.

显而易见的解决方案是使用其他表示法,但是我喜欢这种表示法.有人有解决这个问题的方法吗?

Obvious solution is to use a different notation, but I like this notation. Anyone has a solution for this problem?

推荐答案

我希望我不迟于回答.

templatename.nl-NL.cshtml添加为嵌入式资源时,它将以nl-NL语言的资源降落在附属程序集中.

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

如果转到bin/debug目录,则会在其中找到nl-NL文件夹的nl-NL文件夹.

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

如果反汇编此程序集,则会在其中找到templatename.cshtml文件.

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是我拥有所有资源的命名空间.上面的代码只有在已经加载的情况下才会得到汇编.我以为是.

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
    }

示例项目文件此处.

这篇关于程序集中包含区域性名称的程序集中的嵌入式资源将不会加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆