gpt4 book ai didi

c# - 如何将 HTML 代码放入 .resx 资源文件?

转载 作者:太空狗 更新时间:2023-10-29 16:51:31 25 4
gpt4 key购买 nike

奇怪,之前没有人问过这个......

我正在为 4 种语言创建模板化 HTML 电子邮件。我想将 HTML 模板放入我的 .resx 文件中,以便从代码中轻松、国际化地访问它们。像这样:

.resx 文件:

<data name="BodyTemplate" xml:space="preserve">
<value><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
<title>Title</title>
...
</body>
</html>
</value>
</data>

但是,很明显,编译器会提示 .resx 文件中的 HTML。 有没有办法在 .resx 文件中使用 HTML(或 XML)。怎么办?

如果重要的话,我正在使用 .NET 版本 4 和 dotLiquid 作为模板引擎。

最佳答案

建议:创建你想要的文件,按照你想要的方式命名,例如“my_template.html”然后将此文件添加到您的项目中。

点击它,然后在属性窗口中选择“Build Action”并将其设置为“Embedded Resource”。

无论什么时候你想访问这个文件,你都可以使用这样的东西(没有正确使用 block :

    public static string ReadTextResourceFromAssembly(string name)
{
using ( var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( name ) )
{
return new StreamReader( stream ).ReadToEnd();
}
}

根据您的需要量身定制。上面的方法获取资源,假设你把你的资源放在你的项目MyProject的子目录“HtmlTemplates”中,并命名为“my_template.html”,那么你可以通过名称访问它MyProject.HtmlTemplates.my_template.html

然后你可以将它写入文件或直接使用它等。

这有一些主要的好处:您可以在项目中看到您的 html 文件,它具有 html 扩展名,因此在 Visual Studio 中编辑它具有语法突出显示和适用于 .html 文件的所有工具。

我的单元测试有很多这样的方法,这个方法将数据提取到文件中:

    public static void WriteResourceToFile(string name, string destination)
{
using ( var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( name ) )
{
if ( stream == null )
{
throw new ArgumentException( string.Format( "Resource '{0}' not found", name), "name" );
}

using ( var fs = new FileStream( destination, FileMode.Create ) )
{
stream.CopyTo( fs );
}
}
}

关于c# - 如何将 HTML 代码放入 .resx 资源文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28558336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com