ozdrgnaDiies
ozdrgnaDiies

Reputation: 1929

CodeDom Compiler for C#

I have been trying to get CodeDom to work so I can dynamically create code for my application during runtime. However, after many tutorials and trial and error, I have come into a problem I can't seem to pass. I keep getting compiler errors on code that looks exactly like it should. I get "Unrecognized escape sequence '\'" when there is no '\' anywhere in my code.

The errors I get are all on line 1. Here they are in order: CS1009 CS1056 (3 times in a row) CS0116

Here is what I have:

The code being compiled:

using System;
using System.Windows.Forms;
namespace sdjkfhj 
{    
    public class Sample 
    {
        public static void main()
        {
            MessageBox.Show("Working");
            return;
        }
    }
}

And the compiler code is as follows:

public void Compile(string file)
    {
        var prov = new Dictionary<string, string>();
        prov.Add("CompilerVersion", "v2.0");
        CSharpCodeProvider c = new CSharpCodeProvider();
        ICodeCompiler comp = c.CreateCompiler();

        CompilerParameters param = new CompilerParameters();
        param.GenerateExecutable = true;
        param.OutputAssembly = file + ".exe";
        param.ReferencedAssemblies.Add("System.dll");
        param.ReferencedAssemblies.Add("System.Windows.Forms.dll");
        if (c.Supports(GeneratorSupport.EntryPointMethod))
            param.MainClass = "Sample";

        CompilerResults results = comp.CompileAssemblyFromSource(param, file);

        if (results.Errors.Count > 0)
        {
            foreach (CompilerError CompErr in results.Errors)
            {
                MessageBox.Show("Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine);
            }
        }
    }

Is there something I'm not doing to compile it right? Are there things I'm missing? I'm kind of lost here. Thanks in advance.

Upvotes: 2

Views: 6534

Answers (1)

mlorbetske
mlorbetske

Reputation: 5649

Three things come to mind right away:

  1. There are no semicolons in the code you're attempting to compile.
  2. If Main is supposed to be your entry point, make it static.
  3. Make your source file different than your target file (something like param.OutputAssembly = file + ".exe";

Fixing these is really only the first step, you'll also have to configure the assemblies that your output will need to reference, and it wouldn't be a bad idea to set MainClass on the CompilerParameters you're using either.

A nice example on MSDN

Upvotes: 5

Related Questions