csproj: how to get all resources?

﹥>﹥吖頭↗ 提交于 2019-12-03 21:33:41

Project files are NOT simple XML files, they can contain logic which needs to be evaluated.

You can achieve that by using the Microsoft.Build assembly and the Microsoft.Build.Evaluation namespace.

var project = new Project(@"..\..\StackOverflow.csproj");

        var itemsToCopy = new List<ProjectItem>();

        var projectItems = project.Items;
        foreach (var projectItem in projectItems)
        {
            // e.g get all elements with CopyToOutputDirectory == "Always"
            var projectMetadata = projectItem.GetMetadata("CopyToOutputDirectory");
            if (projectMetadata != null && projectMetadata.EvaluatedValue == "Always")
                itemsToCopy.Add(projectItem);
        }

        foreach (var projectItem in itemsToCopy)
        {
            // e.g get then Include-Attribute from <None Include="Configs\Config.config">
            var evaluatedInclude = projectItem.EvaluatedInclude;
        }

        // get the resources that are not set to CopyToOutputDirectory == "Always"
        var collection = project.GetItems("Resources");
        var resources = collection.Except(itemsToCopy);
        foreach (var projectItem in resources)
        {
            // e.g get then Include-Attribute from <Resource Include="Resources\Icons\icon8.png" />
            var evaluatedInclude = projectItem.EvaluatedInclude;
        }

UPDATE

This should give a general idea how to do certain tasks with project files.

You can get parent element of CopyToOutputDirectory tag via it's Parent property. Also don't forget to get resources which are copied if newer:

XDocument xdoc = XDocument.Load(filePath);
var resources = from r in xdoc.Descendants("Resource")
                select (string)r.Attribute("Include");

var copiedContent = from c in xdoc.Descendants("CopyToOutputDirectory")
                    where (string)c == "Always" || (string)c == "PreserveNewest"
                    select (string)c.Parent.Attribute("Include");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!