C# Convert MarkDown to HTML

Date: 2024-05-15

https://github.com/xoofx/markdig

https://www.nuget.org/packages/Markdig

using Markdig;
using Markdig.Extensions.AutoLinks;

public interface IMarkdownConverter
{
    string ConvertMarkdownToHtml(string markdown);
}

public class MarkdownConverter : IMarkdownConverter
{
    private MarkdownPipeline pipeline;

    public MarkdownConverter()
    {
        pipeline = new MarkdownPipelineBuilder()
            .UseAdvancedExtensions()
            .UseSoftlineBreakAsHardlineBreak()
            .UseAutoLinks(new AutoLinkOptions
            {
                OpenInNewWindow = true,
            })
            .Build();
    }

    public string ConvertMarkdownToHtml(string markdown)
    {
        if (string.IsNullOrWhiteSpace(markdown)) return string.Empty;
        try
        {
            return Markdown.ToHtml(markdown, pipeline);
        }
        catch (Exception ex)
        {
            DomainPorts.Logger.Warning($"Can not convert message from markdown to html: '{markdown}'", ex);
        }
        return markdown;
    }
}
85520cookie-checkC# Convert MarkDown to HTML