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


  • William Chang

    “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

    • http://www.dotnetthoughts.net/ Anuraj P

      @William Chang : I dropped the idea :D I am working on some other personal projects :) Visit project link. Thank you for visiting