How to compile C# code snippet in runtime

Yesterday one of colleague called me and asked how I can compile code from a text source. I explored System.CodeDom classes. And I found one way to create executable (libraries too) using CSharpCodeProvider class.

using (CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider())
{
    this._OutPutFile = Path.ChangeExtension(Path.GetTempFileName(), ".exe");
    CompilerParameters parameters = new CompilerParameters()
    {
        //For creating DLLs it should be false
        GenerateExecutable = true,
        OutputAssembly = this._OutPutFile,
        //For displaying warnings in the compilerResults
        WarningLevel = 4    
    };
    //I am reading the text from a WPF RichTextbox
    TextRange textRange =
        new TextRange(this.txtEditor.Document.ContentStart,
            this.txtEditor.Document.ContentEnd);
    CompilerResults compilerResults =
        csharpCodeProvider.CompileAssemblyFromSource(parameters, textRange.Text);
}

For more details you can found in MSDN

DotNet Snippet compiler (I created a WPF application which used to compile C# snippets, I will make it open source soon.) running on my system.

WPF Snippet compiler

WPF Snippet compiler

2 thoughts on “How to compile C# code snippet in runtime

  1. “I created a WPF application which used to compile C# snippets, I will make it open source soon”

    Any idea when this will be open source? :D

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>