2012-04-26 47 views
1

我有一個將源文件編譯爲可執行文件的小應用程序。問題是這個應用程序需要Netframework 4工作,因此,編譯後的應用程序還需要Net Framework 4.0如何從源文件編譯程序時將目標框架設置爲v2.0或v3.5而不是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; 
} 

任何幫助,將不勝感激! Thankyou提前

+0

如何使用進程。從csc.exe開始,該文件是否可以在Windows XP上運行? – 2012-04-26 14:07:23

+0

如果您無法確定機器上是否有csc.exe,請將其與您的程序一起使用;將其包含在安裝中以便知道您將擁有3.5版本。它肯定會在XP上運行。 – Servy 2012-04-26 14:10:36

+0

但是如何在將csc.exe包含到目錄後使用它?你可以請發佈這個答案!謝謝 – 2012-04-26 14:13:06

回答

5

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

無論指定哪個VS 2010目標版本(2.0,3.0或3.5,4.0),默認情況下它都是2.0。

爲了針對4.0框架,提供供應商的構造一個IDictionary實例如下圖所示

你可以通過使用下面的構造編譯器選項:

var providerOptions = new Dictionary<string, string>(); 
providerOptions.Add("CompilerVersion", "v4.0"); 
var compiler = new CSharpCodeProvider(providerOptions); 
相關問題