2012-04-26 6 views
1

私はソースファイルを実行可能にコンパイルする小さなアプリケーションを持っています。問題は、このアプリケーションではNetframework 4が動作することが必要なため、コンパイルされたものでもNet Framework 4.0が必要です。ソースファイルからプログラムをコンパイルするときに、ターゲットフレームワークを4.0ではなくv2.0またはv3.5に設定するにはどうすればよいですか?

コンパイル済みアプリケーションで使用するターゲットフレームワークの下の関数を設定するにはどうすればよいですか?

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; 
} 

ご協力いただきありがとうございます。前もってありがとうございます

+0

プロセスを使用する方法。 Windows XPでcsc.exeを起動しますか? –

+0

マシンにcsc.exeがインストールされていることを確認できない場合は、プログラムと一緒に持ってきてください。あなたはあなたが3.5バージョンを持っていることを知っているようにそれをインストールに含めてください。それはXPで動作します。 – Servy

+0

しかし、csc.exeをディレクトリに組み込んだ後でそれを使うには?答えとして投稿してください。ありがとうございました –

答えて

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); 
関連する問題