string strCode = @" using System; using System.Text; using System.Collections.Generic; using System.Linq; using System.IO; using System.Reflection; namespace aaaa { public class Program { static void Main(string[] args) { GetDoc(""Testdoc.doc""); Console.WriteLine(""輸出成功""); Console.ReadLine(); } public static void GetDoc(string name) { try { Assembly ass = Assembly.GetExecutingAssembly(); Stream ss = ass.GetManifestResourceStream(name); if (ss != null) { byte[] buffer = new byte[ss.Length]; ss.Read(buffer, 0, buffer.Length); File.WriteAllBytes(Environment.CurrentDirectory + ""\\ProbeDoc.doc"", buffer); } } catch { Console.WriteLine(""error""); } } } }"; CompilerParameters objCompilerParams = new CompilerParameters(); objCompilerParams.GenerateExecutable = true; //編譯成exe還是dll objCompilerParams.GenerateInMemory = false; //是否寫入內存,不寫入內存就寫入磁盤 objCompilerParams.OutputAssembly = "F:\\abcd.exe"; //輸出路徑 objCompilerParams.IncludeDebugInformation = false; //是否產生pdb調試文件 默認是false objCompilerParams.ReferencedAssemblies.Add("System.dll"); objCompilerParams.ReferencedAssemblies.Add("System.Core.dll"); objCompilerParams.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); objCompilerParams.EmbeddedResources.Add("D:\\Testdoc.doc"); //編譯器選項:編譯成(存儲在內存中)的DLL /*objCompilerParams.CompilerOptions = "/target:library /optimize"; //編譯時在內存輸出 objCompilerParams.GenerateInMemory = true; //不生成調試信息 objCompilerParams.IncludeDebugInformation = false;*/ //創建編譯類 CSharpCodeProvider objCompiler = new CSharpCodeProvider(); //進行編譯 CompilerResults objCompileResults = objCompiler.CompileAssemblyFromSource(objCompilerParams, strCode); //獲取編譯結果:程序集 Assembly objAssembly = objCompileResults.CompiledAssembly; ////獲取編譯成的程序集的信息 //object objMainClassInstance = objAssembly.CreateInstance("Program"); //Type objMainClassType = objMainClassInstance.GetType(); ////調用程序集中的類,執行類中的方法,得到結果 //objMainClassType.GetMethod("Main").Invoke(objMainClassInstance, null); //objMainClassType.GetMethod("PrintWorld").Invoke(objMainClassInstance, null);
