Click here to Skip to main content
6,631,404 members and growing! (16,235 online)
Email Password   helpLost your password?
Languages » C# » Applications     Intermediate

C# Compiler

By Konrad Rotuski

A simple C# [VB.NET] compiler without using csc.exe
C#, VC7.NET 1.0, Win2K, Dev
Posted:6 Mar 2002
Views:272,620
Bookmarked:71 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
36 votes for this article.
Popularity: 5.49 Rating: 3.53 out of 5
3 votes, 13.0%
1
2 votes, 8.7%
2
1 vote, 4.3%
3
6 votes, 26.1%
4
11 votes, 47.8%
5

Sample Image - compiler1.jpg

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 :( ). 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

About the Author

Konrad Rotuski


Member
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.
Occupation: Web Developer
Location: Poland Poland

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 52 (Total in Forum: 52) (Refresh)FirstPrevNext
GeneralMy vote of 1 PinmemberParesh Gheewala21:21 1 Dec '08  
GeneralRe: My vote of 1 PinmemberJon_Boy15:14 30 Dec '08  
Generalprofiling library PinmemberMember 40372158:25 19 Aug '08  
GeneralC# Compiler PinmemberReza Aghazadeh20:15 11 May '08  
GeneralPosting on a dead forum! Pinmembermax2929714:30 24 Jun '07  
Questioncompiling projects which refer dlls! Pinmembersamtam23:11 26 Jul '06  
AnswerRe: compiling projects which refer dlls! Pinmembershaz jazz23:36 26 Jul '06  
GeneralYou ARE still using csc.exe, albiet indirectly Pinmemberflaming red dingo15:57 12 Dec '05  
GeneralBackground console Pinmemberberoni6:58 1 Sep '05  
GeneralRe: Background console PinmemberWizard_018:49 11 Sep '05  
GeneralRe: Background console PinmemberHossam™… Ahmed9:57 9 Jul '07  
GeneralStrong Name Key PinmemberkumagKayo21:48 26 Jun '05  
GeneralRe: Strong Name Key PinmemberWizard_0112:17 13 Jul '05  
GeneralRe: Strong Name Key PinmemberkumagKayo15:52 13 Jul '05  
GeneralRe: Strong Name Key PinmemberWizard_0120:08 13 Jul '05  
Generalcompiler , what shall i do ?C# compiler PinsussAnonymous3:50 28 Dec '04  
GeneralUncompiled Code Execution at Runtime Pinmemberpatsissons22:32 10 Dec '04  
Generalc# compiler research work PinsussNinoil Aguilar20:57 12 Jul '04  
GeneralUnload a DLL Reference in VB.NET PinsussJavier Ayala10:14 24 Dec '03  
GeneralRe: Unload a DLL Reference in VB.NET PinmemberPrincesse12:51 10 Feb '05  
Generalwhere can i get c# compiler and editor? pls! Pinsusskyaw0218:03 16 Jul '03  
GeneralRe: where can i get c# compiler and editor? pls! PinsussCreated by: X20:22 22 Jul '03  
GeneralRe: where can i get c# compiler and editor? pls! PinsussAlan Schuetz16:46 10 Dec '03  
GeneralRe: where can i get c# compiler and editor? pls! PinsussAlan Schuetz16:49 10 Dec '03  
GeneralScripting in own apps? PinmemberJodokos13:18 12 Jun '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 6 Mar 2002
Editor: Chris Maunder
Copyright 2002 by Konrad Rotuski
Everything else Copyright © CodeProject, 1999-2009
Web17 | Advertise on the Code Project