How to access the MSBuild 's properties list when coding a custom task?

余生长醉 提交于 2019-12-17 19:44:38

问题


I need to write a custom task that print all the defined properties (the non-reserved ones). So in my C# code, I wanna access to the properties list of MSBuild engine and I don't know how. Please help.


回答1:


The previous example will lock you project file. This may cause problems. For example if you call the task several times in the same project file. Here is improved code:

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;
            }
        }
    }
}



回答2:


Using .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;
        }
    }
}


来源:https://stackoverflow.com/questions/2772426/how-to-access-the-msbuild-s-properties-list-when-coding-a-custom-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!