gpt4 book ai didi

c# - .NET,C# : RazorEngine, 从项目文件夹中解析模板 CsHtml 文件

转载 作者:太空宇宙 更新时间:2023-11-03 22:38:37 25 4
gpt4 key购买 nike

我有以下项目结构:

Solution
Project
Properties/
References/
Model/
Message.cs
Views/
Index.cshtml
EmailBuilder/
EmailBuilder.cs
Program.cs

我想从 Index.cshtml 文件中读取所有文本并将我的模型传递给该文件。但是,如果不设置 Copy to Output Directory: Copy if newer,我无法从我的代码中打开 Index.cshtml。我不想将这些文件复制到输出目录,因为我不想让生成电子邮件的用户看到模板文件。这是我目前正在做的:

private static readonly string TemplateFolderPath = 
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Views");

RazorEngineManager.Instance.Razor.AddTemplate("Index",
File.ReadAllText(Path.Combine(TemplateFolderPath, "Index.cshtml")));

如何在不将其复制到输出目录的情况下读取 cshtml 文件?我来自 Java 世界,它就像从类路径解析文本或速度文件一样简单,不需要将文件复制到输出目录。这些文件保留在我的 jar 中。

我如何在 .NET 中执行此操作?

请帮忙。

最佳答案

.NET 中的一个类似技术(我犹豫说“等效”,因为我对 Java 的了解不够深,无法确定)是使用嵌入式资源。将 .cshtml 文件的生成操作设置为嵌入式资源,并使用 Assembly.GetManifestResourceStream 打开包含资源内容的流。

string resourceName = typeof(Program).FullName + ".Views.Index.cshtml";
using (Stream resourceStream = typeof(Program).Assembly.GetManifestResourceStream(resourceName))
{
// Read the contents
}

这假定 Program 类的命名空间是程序集的默认命名空间。通常情况下会出现这种情况,但如果您在项目创建后重命名了一些东西,它可能会不同步,因此请注意这一点。此外,如果找不到资源,流将为 null,因此请务必检查一下。

您还可以使用 Assembly.GetManifestResourceNames 枚举模板。

string prefix = typeof(Program).FullName + ".Views.";
var templates = (from rn in typeof(Program).Assembly.GetManifestResourceNames()
where rn.EndsWith(".cshtml")
select new TemplateInfo
{
Key = Path.GetFileName(rn)
FileName = rn.Substring(prefix.Length)
ResourceName = rn
}).ToList();

现在您有了对象列表(您自己定义 TemplateInfo),其中包含资源名称、文件名和可在模板管理器中使用的键。

这种技术有一个缺点:当您添加新的 CSHTML 文件时,您必须记住将其更改为 Embedded Resource。提示:如果您在 Visual Studio 中复制/粘贴该文件,它会将 Build Action 属性复制到新文件。

关于c# - .NET,C# : RazorEngine, 从项目文件夹中解析模板 CsHtml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53621756/

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