前提:有的人可能人为分析工程的XML文件,但VB与C#工程的XML有一些不同,我曾经采用这样的方式来获取工程信息的数据
但是一旦用户通过VS设置工程的一些属性,则分析XML带来的是很多条件上的判断,所以后来改用如下方式分析工程文件
//Engine实例,必须传入DotNet2.0所在目录
//Microsoft.Build.BuildEngine命名空间下的Engine
- Engine eng = new Engine(GetDotNetRoot());
- private static string GetDotNetRoot()
- {
- Assembly assembly = typeof(int).Assembly;
- return Path.GetDirectoryName(assembly);
- }
//Microsoft.Build.BuildEngine命名空间下的Project
- Project prj = new Project(eng);
- prj.Load(/*this.ProjectFileName*/此参数为工程文件名); //此参数值来源于下面的TASK中的代码
- this._AssemblyName = prj.EvaluatedProperties["AssemblyName"].Value; //程序集名称
- this._Namespace = prj.EvaluatedProperties["RootNamespace"].Value; //根命名空间
- if (prj.EvaluatedProperties["OutputType"].Value.ToLower().CompareTo("library") == 0)
- this._OutExtName = ".dll"; //类库输出类型
- else
- this._OutExtName = ".exe"; //exe输出类型
- this._OutPath = prj.EvaluatedProperties["OutputPath"].Value; //编译后输出的目录
//以下代码段得到,编译输出的文件名含有绝对路径
- char DiskVolumeChar = Path.VolumeSeparatorChar;
- if (this._OutPath.IndexOf(DiskVolumeChar) > -1)
- this._OutBinaryName = Path.Combine(this._OutPath, this._AssemblyName + this._OutExtName);
- else
- {
- FileInfo finfo = new FileInfo(this.ProjectFileName);
- this._OutBinaryName = Path.Combine(finfo.DirectoryName, this._OutPath);
- DirectoryInfo dinfo = new DirectoryInfo(this._OutBinaryName);
- this._OutBinaryName = Path.Combine(dinfo.FullName, this._AssemblyName + this._OutExtName);
- }
- FileInfo fchk = new FileInfo(this._OutBinaryName);
- if (!fchk.Exists) this._OutBinaryName = string.Empty;
//分析工程文件主要用于自定义编译的任务,也可能,分析工程文件中的信息,也有助于编写VS的ADDIN插件,其中本人在编写插件时使用过,需要工程中的信息数据
//比如,为完成编译后AOP静态注入,(不是在程序运行时执行代码注入)
- public class AopBuildTask : Microsoft.Build.Utilities.Task
- {
- public override bool Execute()
- {
- string prjFileName = this.BuildEngine.ProjectFileOfTaskNode;
- /*
- 上面的代码中所使用的此变量
- prj.Load(prjFileName);
- */
- AopTaskHelper.Log = this.Log;
- AopTaskHelper.Waveing(prjFileName);
- return true;
- }
- }
如果转载请注明出处