2

How can I programmatically add an item to a project?

Something similar to

public void AddExistingItem(string projectPath, string existingItemPath)
{
    //I'm making up the Project class here as an example
    Project p = new Project(projectPath);
    p.AddExistingItem(existingItemPath);
}

I want to mimic Visual Studio's Add Existing Item functionality.

Add Existing Item

Mark Rucker
  • 6,952
  • 4
  • 39
  • 65

3 Answers3

3

VisualStudio project is just a XML file so you can open it using XDocument or XmlDocument and edit.

Denis Palnitsky
  • 18,267
  • 14
  • 46
  • 55
2

Add a reference to EnvDTE.dll, and then use ProjectItems.AddFromFile method
As you can read on this page, you must set the Embed Interop Types property of the assembly to false if you add a reference to EnvDTE.dll

ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
  • The link provided provide instructions to create a new project. How can you add a new Item in an existing project? Could you provide any helpful link? – user8657231 Jan 28 '21 at 23:50
  • 1
    @user8657231 I'm sorry, I wrote this answer more than 7 years ago and have no clue about this situation anymore. Your search is as good as mine. – ProgramFOX Jan 28 '21 at 23:53
0

Try something like this:

public void createProjectItem(DTE2 dte)
{
    //Adds a new Class to an existing Visual Basic project.
    Solution2 soln;
    Project prj;
    soln = (Solution2)_applicationObject.Solution;
    ProjectItem prjItem;
    String itemPath;
    // Point to the first project (the Visual Basic project).
    prj = soln.Projects.Item(1);
    // Retrieve the path to the class template.
    itemPath = soln.GetProjectItemTemplate("Class.zip", "vbproj");
    //Create a new project item based on the template, in this
    // case, a Class.
    prjItem = prj.ProjectItems.AddFromTemplate(itemPath, "MyNewClass");
}

from: http://msdn.microsoft.com/en-us/library/vstudio/ms228774.aspx

Jean-François Beaulieu
  • 4,305
  • 22
  • 74
  • 107