簡體   English   中英

從源文件編譯程序時,如何將目標框架設置為v2.0或v3.5而不是4.0?

[英]How to set the target framework to v2.0 or v3.5 instead of 4.0 when compiling a program from a source file?

我有一個小型應用程序,它將源文件編譯為可執行文件。 問題在於此應用程序需要Netframework 4才能工作,因此,已編譯的應用程序也需要Net Framework 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;
}

任何幫助,將不勝感激 ! 先感謝您

如果您使用CodeDomProvider在VS 2008中以編程方式自己編譯代碼,那么目標是哪個版本的Framework?

默認情況下,它是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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM