How to access project XML from a VS 2013 extension RRS feed

  • Question

  • I'm working on a Visual Studio extension that needs to directly modify a project's msbuild file (e.g. *.csproj). Unfortunately, the Visual Studio SDK doesn't seem to publicly expose any objects that support this.

    If all else fails, I can always create a Microsoft.Build.Evaluation.Project object based on the file after a save event, make my edits there, then re-save. However, this would force the user to reload their project, which I'd prefer to avoid.

    A better partial solution is described in this thread. Visual Studio keeps some of its evaluated objects in ProjectCollection.GlobalProjectCollection and smoothly detects any changes that I make via my extension. Unfortunately, this doesn't seem to work for all project types; it works great for C# but the global collection is left empty when I load a C++ project.

    Does anyone know of a good, supported way to access the evaluated project objects? Failing that, is there a solution that doesn't involve forcing a project reload?

    The extension needs to be compatible with Visual Studio 2013+ but doesn't need to support older versions.

    Tuesday, April 21, 2015 4:02 PM


  • Hi bergbria,

    Try ProjectRootElement object, which provides static method to open the project file and modify the project file. And it does not force the project to reload. For example, try this code snippet, which modifies the AssemblyName property of the project:

    EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));
                EnvDTE.Project project = dte.Solution.Projects.Item(1);
                ProjectRootElement root = ProjectRootElement.Open(project.FullName);
                var props = root.Properties;
                foreach (var prop in props)
                    if (prop.Name == "AssemblyName")
                        prop.Value = "ConsoleApplication111";
    You need to add reference to Microsoft.Build.dll into your project firstly.

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Caillen Tuesday, May 5, 2015 8:31 AM
    Thursday, April 23, 2015 2:24 AM