1

我有一个将源文件编译成可执行文件的小应用程序。问题是这个应用程序需要网络框架 4 才能工作,因此编译的应用程序也需要网络框架 4.0

如何设置目标框架下的函数以在编译的应用程序中使用?

  public static bool CompileExecutable(String sourceName)
{
//Source file that you are compliling 
FileInfo sourceFile = new FileInfo(sourceName);
//Create a C# code provider 
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//Create a bool variable for to to use after the complie proccess to see if there are any erros
bool compileOk = false;
 //Make a name for the exe
 String exeName = String.Format(@"{0}\{1}.exe",
 System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_"));
 //Creates a variable, cp, to set the complier parameters
 CompilerParameters cp = new CompilerParameters();
 //You can generate a dll or a exe file, in this case we'll make an exe so we set this to true
 cp.GenerateExecutable = true;
 //Set the name
 cp.OutputAssembly = exeName;
 //Save the exe as a physical file
 cp.GenerateInMemory = false;
 //Set the compliere to not treat warranings as erros
 cp.TreatWarningsAsErrors = false;
 //Make it compile 
 CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName);
 //if there are more then 0 erros...
 if (cr.Errors.Count > 0)
 {
     //A message box shows the erros that occured 
     MessageBox.Show("Errors building {0} into {1}" +
         sourceName + cr.PathToAssembly);
     //for each error that occured in the code make a separete message box
     foreach (CompilerError ce in cr.Errors)
     {
         MessageBox.Show("  {0}" + ce.ToString());
     }
 }
 //if there are no erros...
 else
 {
     //a message box shows compliere results and a success message
     MessageBox.Show("Source {0} built into {1} successfully." +
         sourceName + cr.PathToAssembly);
 }
 //if there are erros...
 if (cr.Errors.Count > 0)
 {
     //the bool variable that we made in the beggining is set to flase so the functions returns a false
     compileOk = false;
 }
 //if there are no erros...
 else
 {
     //we are returning a true (success)
     compileOk = true;
 }
 //return the result
 return compileOk;
}

任何帮助,将不胜感激 !先感谢您

4

1 回答 1

5

如果您在 VS 2008 中使用 CodeDomProvider 以编程方式自己编译代码,那么该框架的目标版本是什么?

默认情况下它是 2.0,无论指定哪个 VS 2010 目标版本(2.0、3.0 或 3.5、4.0)。

为了以 4.0 框架为目标,请在提供程序的构造函数中提供一个 IDictionary 实例,如下所示

您可以使用以下构造函数将选项传递给编译器:

var providerOptions = new Dictionary<string, string>();
providerOptions.Add("CompilerVersion", "v4.0");
var compiler = new CSharpCodeProvider(providerOptions);
于 2012-04-27T09:13:06.740 回答