I'm currently learning about compiling C# code into thier own exe files. It's really fascinating how it works!
So far I've got this really small application which should convert text being put in to a textbox to C# code which it kinda does but it keeps telling me to add references everytime I press "Build" and I dont know why.
Here is the source code:
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace SimpleBuilder
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// store code
/// select what features
/// print out textfile with all the code from the features
/// compile that textfileContent to a exe
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void fakeMessageOne()
{
Messagebox.Show("Hello World");
}
private void button_Click(object sender, RoutedEventArgs e)
{
CSharpCodeProvider csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", frameworkTextbox.Text } });
CompilerParameters parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, outputTextbox.Text, true);
parameters.GenerateExecutable = true;
CompilerResults result = csc.CompileAssemblyFromSource(parameters, sourceTextbox.Text);
if (result.Errors.HasErrors)
{
result.Errors.Cast<CompilerError>().ToList().ForEach(error => errorTextbox.Text += error.ErrorText + "\r\n");
}
else
{
errorTextbox.Text = "--- Build Succeeded! ---";
}
}
}
}
Here are the errors its throwing me
The type or namespace name 'CSharp' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
The type or namespace name 'CodeDom' does not exist in the namespace 'System' (are you missing an assembly reference?)
The type or namespace name 'Windows' does not exist in the namespace 'System' (are you missing an assembly reference?)
The type or namespace name 'Window' could not be found (are you missing a using directive or an assembly reference?)
The code im trying to compile inside of my application:
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace SimpleBuilder
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// store code
/// select what features
/// print out textfile with all the code from the features
/// compile that textfileContent to a exe
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void fakeMessageOne()
{
Messagebox.Show("Hello World");
}
}
}
And for what its worth here is a image of the small application
You should put your references in with
CompilerParameters.ReferencedAssemblies.Add()