在C#程序编译另一个程序的实现方法

1、C#程序编译编译前,要用到VS2005提供的一个编译工具 devenv.exe,这个在VS安装目录\Common7\IDE 下可以使用控制台命令:

 
 
 
  1. devenv /rebuild debug "【sln path】" 

2、C#程序编译在代码中要运行指定的程序,可以使用process方法:

 
 
 
  1. using System.Diagnostics  
  2. System.Diagnostics.Process.StartInfo   
  3. info=new StartInfo();   
  4. info.FileName="你想要用的特定的程序";   
  5. Info.Arguments="要打开的文件:;   
  6. System.Diagnostics.Process.Start(info);   

3、在C#程序编译的实际使用过程中会遇到一个问题:各人VS安装目录不同,程序中调用devenv的路径就不同。解决这个问题的方法就是读取注册表中的vs的ApplicationPath键值(这个在前面有过介绍)综上,实现方法如下:

 
 
 
  1. using System.Diagnostics;  
  2. using Microsoft.Win32;  
  3.  
  4. private const string REGISTKEY ="  
  5. SOFTWARE\\Microsoft\\MSEnvCommunityContent  
  6. \\ContentTypes\\Addin\\ContentHosts\\  
  7. 1.0\\Visual Studio 2005";  
  8.  
  9. RegistryKey rkey = Registry.LocalMachine;  
  10. //The second parameter tells it to open   
  11. the key as writable  
  12. RegistryKey rkey1 = rkey.OpenSubKey  
  13. (REGISTKEY, true);  
  14. string visualStudio8Path = rkey1.GetValue(  
  15. "ApplicationPath").ToString();  
  16.  
  17. ProcessStartInfo startInfo =   
  18. new ProcessStartInfo(visualStudio8Path);  
  19. startInfo.Arguments = "/rebuild debug " 
  20.                 + "【sln path】";  
  21.  
  22. Process process = new Process();  
  23. process.StartInfo = startInfo;  
  24.  
  25. process.Start();  
  26. process.WaitForExit(); 

【编辑推荐】

  1. C#中定义装箱和拆箱详解
  2. 浅谈C#类型系统
  3. 三种不同的C#异常类型
  4. 详细介绍C#编译器
  5. C#异常机制的相关解释
THE END