Mark Rucker
Mark Rucker

Reputation: 8085

How to Add an Existing Item to a Project Programmatically?

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

Upvotes: 2

Views: 7402

Answers (3)

ProgramFOX
ProgramFOX

Reputation: 6390

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

Upvotes: 2

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

Upvotes: 0

Denis Palnitsky
Denis Palnitsky

Reputation: 18387

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

Upvotes: 3

Related Questions