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?
How to open a CSPROJ file. CSPROJ files are are meant to be opened and edited in Microsoft Visual Studio (Windows, Mac) as part of Visual Studio projects. However, because CSPROJ files are XML files, you can open and edit them in any text or source code editor.
What is a CSProj file? Files with CSPROJ extension represent a C# project file that contains the list of files included in a project along with the references to system assemblies. When a new project is initiated in Microsoft VIiual Studio, you get one . csproj file along with the main solution (. sln) file.
csproj files (WebApi is the name of my project). It is located as expected in the root of the project.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With