我正在尝试实现一个网站,用户可以在文本框中编写一些c#代码并生成.exe文件。我找到了csharpcodeprovider类,它可以创造奇迹。但我想强制.exe生成的文件下载,以便用户可以在本地保存。我试过使用一些fileinfo但是当我运行时,它显示文件没有退出。如果我使用de process class来运行它,它可以工作。
如何完成下载?
这是我的代码
private void button1_Click(object sender, System.EventArgs e)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
string Output = "Output.exe";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = icc.CompileAssemblyFromSource(parameters, textBox1.Text);
if (results.Errors.Count > 0)
{
textBox2.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
txtError.Text = textBox2.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
textBox2.ForeColor = Color.Blue;
textBox2.Text = "Success!";
//If we clicked run then launch our EXE
if (ButtonObject.Text == "Run") Process.Start(Output);
}
//I've tried this to find the .exe file
string filename = Output;
if (filename != "")
{
string path = Server.MapPath(filename);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)//--file doesn't exist
{
Response.Clear();
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}