我做了一个简单的编译器来了解CodeDom。但它不起作用,当我尝试打开我的编译文件时它什么都不做。
当我运行代码并选择一个目录来保存exe文件时,会生成exe文件,但是当我单击exe文件时它什么也没做。
建设者:
using System;
using System.IO;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Windows.Forms;
namespace TestBuilder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void build(string output, string title, string msg)
{
CompilerParameters p = new CompilerParameters();
p.GenerateExecutable = true;
p.ReferencedAssemblies.AddRange(new String[] { "System.dll"});
p.OutputAssembly = output;
p.CompilerOptions = "/t:winexe";
string source = File.ReadAllText(@"C:\Users\Gebruiker\Documents\visual studio 2015\Projects\TestCompiler\Test\Program.cs");
string errors = String.Empty;
source = source.Replace("[MESSAGE]", msg);
CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource(p, source);
if (results.Errors.Count > 0)
{
foreach (CompilerError err in results.Errors)
{
errors += "Error: " + err.ToString() + "\r\n\r\n";
}
}
else errors = "Successfully built:\n" + output;
MessageBox.Show(errors, "Build", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "EXE files (*.exe)|*.exe";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.OK)
{
build(sfd.FileName, textBox1.Text, textBox1.Text);
}
}
}
}
program.cs文件:
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("[MESSAGE]");
Console.ReadLine();
}
}
}
如何解决这个问题,所以当我编译文件并执行它时,它会显示我放在文本框中的消息?
答案 0 :(得分:2)
将p.CompilerOptions = "/t:winexe";
更改为p.CompilerOptions = "/t:exe";
。
之后,编译后的程序应该输出运行它时放在TextBox
内的任何内容。
使用/ target:exe创建控制台应用程序。