public static void ReplaceReference(string csproj_file, string reference_name, bool force) { var stream = new MemoryStream(File.ReadAllBytes(csproj_file)); // cache file in memory var document = XDocument.Load(stream); bool bWasRemoved = RemoveReference(document, reference_name); bool bRequiresSave = bWasRemoved; var xmlNamespaceManager = new XmlNamespaceManager(new NameTable()); xmlNamespaceManager.AddNamespace("ns", MSBuildFile.NamespaceName); XElement group = document.XPathSelectElement("/ns:Project/ns:ItemGroup", xmlNamespaceManager); if (group == null) { // insert new item group throw new NotImplementedException(); } // insert new reference if (force || bWasRemoved) { XNamespace ns = document.Root.Name.Namespace; var newEl = new XElement(ns + "Reference"); var newname = new AssemblyVersionSigned(reference_name); newEl.Add(new XAttribute("Include", newname.Generate())); group.Add(newEl); bRequiresSave = true; } if (bRequiresSave) { document.Save(csproj_file); } }
protected static bool RemoveProjectReference(XDocument document, string reference_name) { bool bWasRemoved = false; var newname = new AssemblyVersionSigned(reference_name); var xmlNamespaceManager = new XmlNamespaceManager(new NameTable()); xmlNamespaceManager.AddNamespace("ns", MSBuildFile.NamespaceName); // remove ProjectReference var itemsToRemove2 = new List <XElement>(); IEnumerable <XElement> listOfReferences2 = document.XPathSelectElements("/ns:Project/ns:ItemGroup/ns:ProjectReference[@Include]", xmlNamespaceManager); foreach (var el in listOfReferences2) { string assRef = el.Attribute("Include").Value; if (assRef.IndexOf(newname.Name, StringComparison.InvariantCulture) >= 0) { itemsToRemove2.Add(el); } } foreach (var item in itemsToRemove2) { Console.WriteLine($"ProjectReference removed {item.ToString()}"); item.Remove(); bWasRemoved = true; } return(bWasRemoved); }