how to open .csproj in xml file through C# code and add a file as a link

I want to add CommonFileInfo.cs in more than one project
for this i want to add "CommonFileInfo.cs" file as a link in project.

So I want to open every .csproj in xml file and add this code.

<Compile Include="..\Projects\CommonFileInfo.cs">

How to do this

Thanks in Advance

Re: Visual C# General how to open .csproj in xml file through C# code and add a file as a link????

Alberto Poblacion

One way to modify an XML file is to load it into a System.Xml.XmlDocument:

using System.Xml;


XmlDocument doc = new XmlDocument();



//Modify "doc"



Now, how do you "modify the document" Well, first you find the node that you want to manipulate and then you chage that node. To find the node you will need a little bit of XPath:

XmlNode nodeItemGroup = doc.SelectSingleNode("//ItemGroup/Compile").ParentNode;

Next, you add your Xml to the node you found:

XmlElement newChild = doc.CreateElement("Compile");

//...Build the content (see example in the online doc for CreateElement(string)

Hope this helps.

Re: Visual C# General how to open .csproj in xml file through C# code and add a file as a link????


The code presumes there is already an ItemGroup for Compile nodes... Anyway, it should get you started...

Code Snippet

static void Main(string[] args)
XmlDocument doc = new XmlDocument(); doc.Load(@"project.xml");

XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("x", "");

XmlNode firstCompileNode = doc.SelectSingleNode("/x:Project/x:ItemGroup/x:Compile", mgr);
XmlNode itemGroupNode = firstCompileNode.ParentNode;

XmlNode newCompileNode = doc.CreateNode(XmlNodeType.Element, "Compile", string.Empty);
XmlAttribute newCompileNodeAttribute = doc.CreateAttribute("Include");
newCompileNodeAttribute.Value = @"..\Projects\CommonFileInfo.cs"; newCompileNode.Attributes.Append(newCompileNodeAttribute);

XmlNode linkNode = doc.CreateNode(XmlNodeType.Element, "Link", string.Empty);
linkNode.InnerText = "CommonFileInfo.cs";


Console.Write("{0}Press any key to continue...", Environment.NewLine);

Seems i'm a bit late with my answer, but i can tell you that without the namespacemanager the SelectSingleNode will not find the wanted node (= figuring that out is what took so long Sad )