Reading the list of References from csproj files

前端 未结 3 1321
心在旅途
心在旅途 2020-12-09 02:12

Does anyone know of a way to programmatically read the list of References in a VS2008 csproj file? MSBuild does not appear to support this functionality. I\'m trying to re

相关标签:
3条回答
  • 2020-12-09 02:49

    Building on @Pavel Minaev's answer, this is what worked for me (notice the added .Attributes line to read the Include attribute)

    XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
        XDocument projDefinition = XDocument.Load(@"D:\SomeProject.csproj");
        IEnumerable<string> references = projDefinition
            .Element(msbuild + "Project")
            .Elements(msbuild + "ItemGroup")
            .Elements(msbuild + "Reference")
            .Attributes("Include")    // This is where the reference is mentioned       
            .Select(refElem => refElem.Value);
        foreach (string reference in references)
        {
            Console.WriteLine(reference);
        }
    
    0 讨论(0)
  • 2020-12-09 02:54

    Based on @PavelMinaev's answer, I also added the "HintPath" Element to the output. I write the string array "references" to a ".txt" file.

    XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
                XDocument projDefinition = XDocument.Load(@"C:\DynamicsFieldsSite.csproj");
                var references = projDefinition
                    .Element(msbuild + "Project")
                    .Elements(msbuild + "ItemGroup")
                    .Elements(msbuild + "Reference")
                    .Select(refElem => (refElem.Attribute("Include") == null ? "" : refElem.Attribute("Include").Value) + "\n" + (refElem.Element(msbuild + "HintPath") == null ? "" : refElem.Element(msbuild + "HintPath").Value) + "\n");
                File.WriteAllLines(@"C:\References.txt", references);
    
    0 讨论(0)
  • 2020-12-09 03:05

    The XPath should be /Project/ItemGroup/Reference, and you have forgot the namespace. I'd just use XLINQ - dealing with namespaces in XPathNavigator is rather messy. So:

        XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
        XDocument projDefinition = XDocument.Load(fullProjectPath);
        IEnumerable<string> references = projDefinition
            .Element(msbuild + "Project")
            .Elements(msbuild + "ItemGroup")
            .Elements(msbuild + "Reference")
            .Select(refElem => refElem.Value);
        foreach (string reference in references)
        {
            Console.WriteLine(reference);
        }
    
    0 讨论(0)
提交回复
热议问题