我目前正在学习如何将C#代码编译到自己的exe文件中。 它的工作原理非常吸引人!
到目前为止,我已经拥有了这个非常小的应用程序,它应该将文本放入文本框中转换为C#代码,但是它一直在告诉我每次按“Build”时都会添加引用,我不知道为什么。
以下是源代码:
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! ---";
}
}
}
}
以下是它抛出的错误
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?)
尝试在我的应用程序内编译的代码:
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");
}
}
}
答案 0 :(得分:2)
您应该使用CompilerParameters.ReferencedAssemblies.Add()