Situ

Hello

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">
<Link>CommonFileInfo.cs</Link>
</Compile>

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();

doc.Load("file.csproj");

...

//Modify "doc"

...

doc.Save("file.csproj");

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)
nodeItemGroup.AppendChild(newChild);

Hope this helps.





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

timvw

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", "http://schemas.microsoft.com/developer/msbuild/2003");

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";

newCompileNode.AppendChild(linkNode);
itemGroupNode.AppendChild(newCompileNode);

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



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 )