BENBUN Coder
BENBUN Coder

Reputation: 4881

Reading a *.CSPROJ file in C#

I am attempting to write some code to read in a *.CSPROJ file using C#

The code I have is as follows

   XmlDocument xmldoc = new XmlDocument();
   xmldoc.Load(fullPathName);

   XmlNamespaceManager mgr = new XmlNamespaceManager(xmldoc.NameTable);
   //mgr.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");

   foreach (XmlNode item in xmldoc.SelectNodes("//EmbeddedResource") )
   {
      string test = item.InnerText.ToString();
   }

using the debugger I can see that 'fullPathName" has the correct value and the xmldoc once loaded has the correct contents.

The xmldoc does not have any "Nodes" though, as if the contents are not recognised as XML.

Using a XML editor the *.csproj file validates an XML document.

Where am I going wrong?

Upvotes: 36

Views: 28306

Answers (3)

Thomas Levesque
Thomas Levesque

Reputation: 292455

Why not use the MSBuild API?

Project project = new Project();
project.Load(fullPathName);
var embeddedResources =
    from grp in project.ItemGroups.Cast<BuildItemGroup>()
    from item in grp.Cast<BuildItem>()
    where item.Name == "EmbeddedResource"
    select item;

foreach(BuildItem item in embeddedResources)
{
    Console.WriteLine(item.Include); // prints the name of the resource file
}

You need to reference the Microsoft.Build.Engine assembly

Upvotes: 61

BrokenGlass
BrokenGlass

Reputation: 160902

For completeness here the XDocument version, this simplifies namespace management:

        XDocument xmldoc = XDocument.Load(fullPathName);
        XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";

        foreach (var resource in xmldoc.Descendants(msbuild + "EmbeddedResource"))
        {
            string includePath = resource.Attribute("Include").Value;
        }

Upvotes: 10

Richard
Richard

Reputation: 30618

You were getting close with your XmlNamespaceManager addition, but weren't using it in the SelectNodes method:

XmlNamespaceManager mgr = new XmlNamespaceManager(xmldoc.NameTable);
mgr.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");

foreach (XmlNode item in xmldoc.SelectNodes("//x:ProjectGuid", mgr))
{
    string test = item.InnerText.ToString();
}

(I switched to searching for a different element as my project didn't have any embedded resources)

Upvotes: 21

Related Questions