Skip to content

RazorEngine Methods

William David Cossey edited this page Jun 7, 2020 · 1 revision

CompileFromFileAsync()

CompileFromFileAsync() uses CompileFromStreamAsync() internally and manages the lifecycle of the StreamReader, disposing it when reading the file has completed.

public void CompileFromFileSample()
{
    RazorEngine razorEngine = new RazorEngine();
    var compiledTemplate = razorEngine.CompileFromFileAsync(@"C:\MyTemplate.cshtml");
    
    ...   
}

CompileFromStreamAsync()

CompileFromStreamAsync() allows (you) the developer to manage the lifecycle of the StreamReader, making it possible to load templates from additional sources (i.e. Resources).

The only caveat to using CompileFromStreamAsync() is that the position of the underlying Stream will be set to 0 (zero) and the buffer cleared.

public void CompileFromStreamSample()
{
    using (streamReader = new StreamReader(@"C:\MyTemplate.cshtml"))
    {
        RazorEngine razorEngine = new RazorEngine();
        var compiledTemplate = razorEngine.CompileFromStreamAsync(streamReader);
        
        ...
    }
}

Code flow

razorEngine.CompileFromFileAsync(string fileName, ...)
    razorEngine.CompileFromStreamAsync(StreamReader streamReader, ...) 
        razorEngine.CompileAsync(string contennt, ...)

Clone this wiki locally