René Beneš
René Beneš

Reputation: 468

Compile code in a textbox and save to exe

Is it possible to compile any given C# code in textbox, and then save it to an exe?

Is this possible? If so, how can it be done?

Upvotes: 0

Views: 984

Answers (2)

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34591

Apart from compiling the code at runtime, you can just save the code from your textbox to disk, and then use csc.exe to compile it. The command would look similar to the following:

%systemroot%\Microsoft.NET\Framework\v3.5\csc /out:filename.exe filename.cs

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

Yes, it is possible. You could use CodeDOM. And here's an example:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Rnge(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

Upvotes: 4

Related Questions