Click here to Skip to main content
11,480,626 members (61,410 online)
Click here to Skip to main content

C# Compiler

, 6 Mar 2002 364.9K 5.6K 104
Rate this:
Please Sign up or sign in to vote.
A simple C# [VB.NET] compiler without using csc.exe
<!-- Download Links --> <!-- Article image -->

Sample Image - compiler1.jpg

<!-- Add the rest of your HTML here -->

Introduction

CSCompiler is a simple application for compiling single file C# source code. It was written in C#. Of course I didn't wrote a whole C# compiler. Instead I've used interfaces provided by the .NET platform.

What you have to do in order to have a C# compiler :

  1. Create an instance of CSharpCodeProvider (VBCodeProvider for Visual Basic)
  2. Obtain interface for ICodeCompiler
  3. Provide CompilerParameters for compiler options
  4. Compile source code using CompileAssemblyFromSource method of ICodeCompiler interface
  5. Process CompilerResults
  6. Execute generated application if there were no errors

That's it.

This scenario uses code provided as a string, but you can also use source files. You can also generate an assembly in memory , but generating binary a application is better for viewing 'physical' result of a compiler.

This simple application forces you to type in a main class of the application (it is not so tricky as it could be Frown | :( ). The assembly references of CSCompiler application should be enough for most of the simplest applications, but if not you must add more assembly references to CompilerParamters to work fine.

The "Compile and Execute" button code look like :

private void button1_Click(object sender, System.EventArgs e)
{
    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
    // For Visual Basic Compiler try this :
    //Microsoft.VisualBasic.VBCodeProvider

    ICodeCompiler compiler = codeProvider.CreateCompiler();
    CompilerParameters parameters = new CompilerParameters();

    parameters.GenerateExecutable = true;
    if (appName.Text == "")    
    {
        System.Windows.Forms.MessageBox.Show(this, 
                               "Application name cannot be empty");
        return ;
    }

    parameters.OutputAssembly = appName.Text.ToString();

    if (mainClass.Text.ToString() == "")
    {
        System.Windows.Forms.MessageBox.Show(this, 
                               "Main Class Name cannot be empty");
        return ;
    }

    parameters.MainClass = mainClass.Text.ToString();
    parameters.IncludeDebugInformation = includeDebug.Checked;

    // Add available assemblies - this should be enough for the simplest
    // applications.
    foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) 
    {
        parameters.ReferencedAssemblies.Add(asm.Location);
    }

    String code = textBox1.Text.ToString();
    //System.Windows.Forms.MessageBox.Show(this, code);

    CompilerResults results = compiler.CompileAssemblyFromSource(parameters, 
                                                                 code);
            
    if (results.Errors.Count > 0) 
    {
        string errors = "Compilation failed:\n";
        foreach (CompilerError err in results.Errors) 
        {
            errors += err.ToString() + "\n";
        }
        System.Windows.Forms.MessageBox.Show(this, errors, 
                               "There were compilation errors");
    }
    else    
    {
        #region Executing generated executable
        // try to execute application
        try 
        {
            if (!System.IO.File.Exists(appName.Text.ToString())) 
            {
                MessageBox.Show(String.Format("Can't find {0}", appName), 
                                "Can't execute.", MessageBoxButtons.OK, 
                                MessageBoxIcon.Error);
                return;
            }
            ProcessStartInfo pInfo = new ProcessStartInfo(appName.Text.ToString());
            Process.Start(pInfo);
        } 
        catch (Exception ex) 
        {
            MessageBox.Show(String.Format("Error while executing {0}", 
                    appName) + ex.ToString(), "Can't execute.", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        #endregion
                
    }
    
}

If you want to know more about CodeProvider interfaces look at NAnt project at sourceforge.

Credits:

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Konrad Rotuski
Web Developer
Poland Poland
At the moment I'm a student at Warsaw University of Technology in Poland.

My programming langugage of choice is C++.
I also like C# and Java.

Comments and Discussions

 
QuestionHello, Sir how I can to deploy windows form database application to other computer Pin
Member 108254999-Sep-14 22:25
memberMember 108254999-Sep-14 22:25 
Generalfrom where i can get c# compiler. Pin
prav.sharma899-Jun-10 16:58
memberprav.sharma899-Jun-10 16:58 
GeneralMy vote of 1 Pin
ilke can19-Feb-10 5:05
memberilke can19-Feb-10 5:05 
GeneralMy vote of 1 Pin
Paresh Gheewala1-Dec-08 21:21
memberParesh Gheewala1-Dec-08 21:21 
GeneralRe: My vote of 1 Pin
Jon_Boy30-Dec-08 15:14
memberJon_Boy30-Dec-08 15:14 
GeneralC# Compiler Pin
Reza Aghazadeh11-May-08 20:15
memberReza Aghazadeh11-May-08 20:15 
GeneralPosting on a dead forum! Pin
max2929724-Jun-07 14:30
membermax2929724-Jun-07 14:30 
Questioncompiling projects which refer dlls! Pin
samtam26-Jul-06 23:11
membersamtam26-Jul-06 23:11 
AnswerRe: compiling projects which refer dlls! Pin
shaz jazz26-Jul-06 23:36
membershaz jazz26-Jul-06 23:36 
GeneralYou ARE still using csc.exe, albiet indirectly Pin
flaming red dingo12-Dec-05 15:57
memberflaming red dingo12-Dec-05 15:57 
You ARE still using csc.exe, albiet indirectly.
The CSharpCodeProvider internally uses csc.exe to compile code, so this article is a bit misleading.


flaming red dingo

GeneralBackground console Pin
beroni1-Sep-05 6:58
memberberoni1-Sep-05 6:58 
GeneralRe: Background console Pin
Wizard_0111-Sep-05 8:49
memberWizard_0111-Sep-05 8:49 
GeneralRe: Background console Pin
Hossam™… Ahmed9-Jul-07 9:57
memberHossam™… Ahmed9-Jul-07 9:57 
GeneralStrong Name Key Pin
kumagKayo26-Jun-05 21:48
memberkumagKayo26-Jun-05 21:48 
GeneralRe: Strong Name Key Pin
Wizard_0113-Jul-05 12:17
memberWizard_0113-Jul-05 12:17 
GeneralRe: Strong Name Key Pin
kumagKayo13-Jul-05 15:52
memberkumagKayo13-Jul-05 15:52 
GeneralRe: Strong Name Key Pin
Wizard_0113-Jul-05 20:08
memberWizard_0113-Jul-05 20:08 
Generalcompiler , what shall i do ?C# compiler Pin
Anonymous28-Dec-04 3:50
sussAnonymous28-Dec-04 3:50 
GeneralUncompiled Code Execution at Runtime Pin
patsissons10-Dec-04 22:32
memberpatsissons10-Dec-04 22:32 
Generalc# compiler research work Pin
Ninoil Aguilar12-Jul-04 20:57
sussNinoil Aguilar12-Jul-04 20:57 
GeneralUnload a DLL Reference in VB.NET Pin
Javier Ayala24-Dec-03 10:14
sussJavier Ayala24-Dec-03 10:14 
GeneralRe: Unload a DLL Reference in VB.NET Pin
Princesse10-Feb-05 12:51
memberPrincesse10-Feb-05 12:51 
Generalwhere can i get c# compiler and editor? pls! Pin
kyaw0216-Jul-03 18:03
susskyaw0216-Jul-03 18:03 
GeneralRe: where can i get c# compiler and editor? pls! Pin
Created by: X22-Jul-03 20:22
sussCreated by: X22-Jul-03 20:22 
GeneralRe: where can i get c# compiler and editor? pls! Pin
Alan Schuetz10-Dec-03 16:46
sussAlan Schuetz10-Dec-03 16:46 
GeneralRe: where can i get c# compiler and editor? pls! Pin
Alan Schuetz10-Dec-03 16:49
sussAlan Schuetz10-Dec-03 16:49 
QuestionScripting in own apps? Pin
Jodokos12-Jun-03 13:18
memberJodokos12-Jun-03 13:18 
GeneralBad code! Pin
Ilia#12-Mar-03 4:12
memberIlia#12-Mar-03 4:12 
GeneralRe: Bad code- NOT! Pin
Anonymous3-Jun-03 17:33
sussAnonymous3-Jun-03 17:33 
GeneralRe: Bad code- NOT! Pin
kumagKayo13-Jul-05 18:09
memberkumagKayo13-Jul-05 18:09 
GeneralA way to implement Business Rules Pin
OPT23-Jul-02 18:11
sussOPT23-Jul-02 18:11 
GeneralRe: A way to implement Business Rules Pin
Feng Qin3-Nov-02 22:38
memberFeng Qin3-Nov-02 22:38 
GeneralStore the assembly in a Database and call it later.... Pin
chrism Muench19-Jun-02 18:07
memberchrism Muench19-Jun-02 18:07 
GeneralRe: Store the assembly in a Database and call it later.... Pin
ChrisInPhoenix19-May-03 13:41
sussChrisInPhoenix19-May-03 13:41 
GeneralRe: Store the assembly in a Database and call it later.... Pin
patsissons10-Dec-04 22:29
memberpatsissons10-Dec-04 22:29 
GeneralWriting the dll to a Directory of your choice Pin
Orion Buttigieg2-May-02 10:37
memberOrion Buttigieg2-May-02 10:37 
GeneralParser vs Compiler Pin
Anonymous16-Apr-02 7:48
memberAnonymous16-Apr-02 7:48 
GeneralRe: Parser vs Compiler Pin
Gerald Schwab20-Jul-02 22:47
memberGerald Schwab20-Jul-02 22:47 
GeneralCool! Neat article. Pin
kaleid17-Mar-02 17:58
memberkaleid17-Mar-02 17:58 
QuestionWhat's the point? Pin
Mr. Tibbs12-Mar-02 2:59
memberMr. Tibbs12-Mar-02 2:59 
AnswerRe: What's the point? Pin
Konrad Rotuski12-Mar-02 3:34
memberKonrad Rotuski12-Mar-02 3:34 
GeneralRe: What's the point? Pin
Anonymous20-Jul-02 22:43
sussAnonymous20-Jul-02 22:43 
GeneralRe: What's the point? Pin
Konrad Rotuski21-Jul-02 3:20
memberKonrad Rotuski21-Jul-02 3:20 
GeneralRe: What's the point? Pin
slotownusa20-Aug-02 7:29
sussslotownusa20-Aug-02 7:29 
GeneralRe: What's the point? Pin
anonomous27-Sep-02 18:20
sussanonomous27-Sep-02 18:20 
GeneralRe: What's the point? Pin
ChrisInPhoenix19-May-03 13:34
sussChrisInPhoenix19-May-03 13:34 
GeneralRe: What's the point? Pin
RKL20-Nov-02 4:11
sussRKL20-Nov-02 4:11 
GeneralRe: What's the point? Pin
Anonymous24-Oct-04 8:09
sussAnonymous24-Oct-04 8:09 
GeneralRe: What's the point? Pin
Anonymous2-Jun-03 3:56
sussAnonymous2-Jun-03 3:56 
GeneralRe: What's the point? Pin
Nathan Ridley10-Mar-04 18:53
memberNathan Ridley10-Mar-04 18:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150520.1 | Last Updated 7 Mar 2002
Article Copyright 2002 by Konrad Rotuski
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid