ASP.NET RazorEngine Save HTML Files

2023-01-08

筆記如何使用 RazorEngine 使用 Razor 語法渲染網頁並且保存為 HTML Files。

logo

說明

using RazorEngine;
using RazorEngine.Templating; // For extension methods.
using System.Reflection;

var service = Engine.Razor;


string workingDirectory = Environment.CurrentDirectory;

string layoutPath = Path.Combine(
    Path.GetDirectoryName(Directory.GetParent(workingDirectory).Parent.Parent.FullName), @"RazorEngine\Views\_Layout.cshtml");

var layout = File.ReadAllText(layoutPath);

Console.WriteLine("Layout Loaded..");

service.AddTemplate("layout", layout);
service.AddTemplate("template", @"@{Layout = ""layout"";}my template");
service.Compile("template");
var result = service.Run("template");

Console.WriteLine("Rendered..");

string currentDirectory = Directory.GetCurrentDirectory();
string fileName = "index.html";
string filePath = Path.Combine(currentDirectory, fileName);

File.WriteAllText(filePath, result);

Console.WriteLine("File Saved..");