2010-05-05 84 views

回答

3

使用.NET 4:

using Microsoft.Build.Evaluation; 
using Microsoft.Build.Utilities; 

namespace MSBuildTasks 
{ 
    public class GetAllProperties : Task 
    { 
    public override bool Execute() 
    { 
     Project project = new Project(BuildEngine.ProjectFileOfTaskNode); 
     foreach (ProjectProperty evaluatedProperty in project.AllEvaluatedProperties) 
     { 
     if (!evaluatedProperty.IsEnvironmentProperty && 
      !evaluatedProperty.IsGlobalProperty && 
      !evaluatedProperty.IsReservedProperty) 
     { 
      string name = evaluatedProperty.Name; 
      string value = evaluatedProperty.EvaluatedValue; 
     } 

     // Do your stuff 
     } 

     return true; 
    } 
    } 
} 
6

前面的例子會鎖定您的項目文件。這可能會導致問題。例如,如果您在同一個項目文件中多次調用任務。這裏是改進的代碼:

using System.Xml; 
using Microsoft.Build.Evaluation; 
using Microsoft.Build.Utilities; 

namespace MSBuildTasks 
{ 
    public class GetAllProperties : Task 
    { 
    public override bool Execute() 
    { 
     using (XmlReader projectFileReader = XmlReader.Create(BuildEngine.ProjectFileOfTaskNode)) 
     { 
     Project project = new Project(projectFileReader); 

     foreach (ProjectProperty property in project.AllEvaluatedProperties) 
     { 
      if (property.IsEnvironmentProperty) continue; 
      if (property.IsGlobalProperty) continue; 
      if (property.IsReservedProperty) continue; 

      string propertyName = property.Name; 
      string propertyValue = property.EvaluatedValue; 

      // Do your stuff 
     } 

     return true; 
     } 
    } 
    } 
}