我的项目结构如下:
Solution
Project
Properties/
References/
Model/
Message.cs
Views/
Index.cshtml
EmailBuilder/
EmailBuilder.cs
Program.cs我想从Index.cshtml文件中读取所有文本,并将我的模型传递给该文件。但是,如果不设置Index.cshtml,则无法从代码中打开Copy to Output Directory: Copy if newer。我不想将这些文件复制到输出目录,因为我不希望生成电子邮件的用户看到模板文件。这就是我目前正在做的事情:
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世界,它就像解析类路径中的文本或速度文件一样简单,它不需要将文件复制到输出目录。文件都藏在我的罐子里了。
我如何在.NET中做到这一点?
请帮帮忙。
发布于 2018-12-04 21:59:37
在.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。提示:如果在Visual中复制/粘贴文件,它将将Build属性复制到新文件中。
https://stackoverflow.com/questions/53621756
复制相似问题