Extract Front Matter from Markdown file in .NET Core using Markdig

Adding YAML front matter to Markdown is a great way to add metadata to your content. Front matter is the first thing in the file and must be added in a special bock. Something similar to following block:

---
title: This can be title of your document
createDate: 2020-06-16
---

To extract this information from your file you can use Markdig. After extraction you can use a library like YamlDotNet to deserialize this content into an object.

This is sample C# code that achieves what discussed above:

var pipeline = new MarkdownPipelineBuilder()
    .UseYamlFrontMatter()
    .Build();

var writer = new StringWriter();
var renderer = new HtmlRenderer(writer);
pipeline.Setup(renderer);

var document = Markdown.Parse(markdown, pipeline);

// extract the front matter from markdown document
var yamlBlock = document.Descendants<YamlFrontMatterBlock>().FirstOrDefault();

var yaml = yamlBlock.Lines.ToString();

// deserialize the yaml block into a custom type
var deserializer = new DeserializerBuilder()
    .WithNamingConvention(CamelCaseNamingConvention.Instance)
    .Build();

var metadata = deserializer.Deserialize<Metadata>(yaml);

// finally we can render the markdown content as html if necessary
renderer.Render(document);
await writer.FlushAsync();
var html = writer.ToString();