原文链接

    1. string strCode = @"
    2. using System;
    3. using System.Text;
    4. using System.Collections.Generic;
    5. using System.Linq;
    6. using System.IO;
    7. using System.Reflection;
    8. namespace aaaa
    9. {
    10. public class Program
    11. {
    12. static void Main(string[] args)
    13. {
    14. GetDoc(""Testdoc.doc"");
    15. Console.WriteLine(""输出成功"");
    16. Console.ReadLine();
    17. }
    18. public static void GetDoc(string name)
    19. {
    20. try
    21. {
    22. Assembly ass = Assembly.GetExecutingAssembly();
    23. Stream ss = ass.GetManifestResourceStream(name);
    24. if (ss != null)
    25. {
    26. byte[] buffer = new byte[ss.Length];
    27. ss.Read(buffer, 0, buffer.Length);
    28. File.WriteAllBytes(Environment.CurrentDirectory + ""\\ProbeDoc.doc"", buffer);
    29. }
    30. }
    31. catch
    32. {
    33. Console.WriteLine(""error"");
    34. }
    35. }
    36. }
    37. }";
    38. CompilerParameters objCompilerParams = new CompilerParameters();
    39. objCompilerParams.GenerateExecutable = true; //编译成exe还是dll
    40. objCompilerParams.GenerateInMemory = false; //是否写入内存,不写入内存就写入磁盘
    41. objCompilerParams.OutputAssembly = "F:\\abcd.exe"; //输出路径
    42. objCompilerParams.IncludeDebugInformation = false; //是否产生pdb调试文件 默认是false
    43. objCompilerParams.ReferencedAssemblies.Add("System.dll");
    44. objCompilerParams.ReferencedAssemblies.Add("System.Core.dll");
    45. objCompilerParams.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
    46. objCompilerParams.EmbeddedResources.Add("D:\\Testdoc.doc");
    47. //编译器选项:编译成(存储在内存中)的DLL
    48. /*objCompilerParams.CompilerOptions = "/target:library /optimize";
    49. //编译时在内存输出
    50. objCompilerParams.GenerateInMemory = true;
    51. //不生成调试信息
    52. objCompilerParams.IncludeDebugInformation = false;*/
    53. //创建编译类
    54. CSharpCodeProvider objCompiler = new CSharpCodeProvider();
    55. //进行编译
    56. CompilerResults objCompileResults = objCompiler.CompileAssemblyFromSource(objCompilerParams, strCode);
    57. //获取编译结果:程序集
    58. Assembly objAssembly = objCompileResults.CompiledAssembly;
    59. ////获取编译成的程序集的信息
    60. //object objMainClassInstance = objAssembly.CreateInstance("Program");
    61. //Type objMainClassType = objMainClassInstance.GetType();
    62. ////调用程序集中的类,执行类中的方法,得到结果
    63. //objMainClassType.GetMethod("Main").Invoke(objMainClassInstance, null);
    64. //objMainClassType.GetMethod("PrintWorld").Invoke(objMainClassInstance, null);