pastebin - collaborative debugging tool
xtremeroot.kpaste.net RSS


Code Compiler (C#)
Posted by Anonymous on Thu 25th Nov 2010 18:06
raw | new post

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.CodeDom.Compiler;
  9. using System.Reflection;
  10. using Microsoft.CSharp;
  11.  
  12. namespace FUDBuilder
  13. {
  14.     public partial class frmMain : Form
  15.     {
  16.         CSharpCodeProvider compiler = new CSharpCodeProvider();
  17.  
  18.         public frmMain()
  19.         {
  20.             InitializeComponent();
  21.         }
  22.  
  23.         private void frmMain_Load(object sender, EventArgs e)
  24.         {
  25.             // some sample code that shows a message box
  26.             string code = "using System; using System.Windows.Forms;\nnamespace TestCode { class TestClass { static void Main() { MessageBox.Show(\"Hello, runtime compiled world!\"); } } }";
  27.             Compile(code, "compiled.exe");
  28.         }
  29.  
  30.         private void Compile(string code, string fileName)
  31.         {
  32.             CompilerParameters cparams = new CompilerParameters();
  33.             cparams.GenerateExecutable = true;                  // we want to build an EXE
  34.             cparams.GenerateInMemory = false;                   // don't generate this in memory
  35.             cparams.OutputAssembly = fileName;                  // set the output file name
  36.             cparams.ReferencedAssemblies.Add("System.dll");
  37.             cparams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
  38.             cparams.CompilerOptions = "/optimize /target:winexe";    // optimise and set the target to a WinForms application (change to /target:exe if you want console)
  39.             // compile
  40.             CompilerResults result = compiler.CompileAssemblyFromSource(cparams, code);
  41.             // if there are errors in the code, tell the user
  42.             foreach (CompilerError error in result.Errors)
  43.             {
  44.                 MessageBox.Show(string.Format("Line {0}: Error {1} - {2}", error.Line, error.ErrorNumber, error.ErrorText));
  45.             }
  46.         }
  47.     }
  48. }

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with {%HIGHLIGHT}





All content is user-submitted.
The administrators of this site (kpaste.net) are not responsible for their content.
Abuse reports should be emailed to us at