Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically add a file to a Solution?

I am developing a VS Package and part of the functionality that I need to implement is to add a file to the Solution Items of the currently open Solution.

This is exactly the same action that would be performed manually if you right-click on a Solution and choose Add > Existing Item. Then selected a file on disk.

I have taken a good look at the DTE and DTE2 interfaces and can see the operations to add and manipulate projects but there doesn't appear to be any operations for adding individual files.

Thanks.

like image 359
Martyn Avatar asked Aug 13 '12 11:08

Martyn


People also ask

How do I add a file to a solution?

Add files to a solution To add an item to a solution, on the context (right-click) menu of the solution node in Solution Explorer, select Add > New Item, or Add > Existing Item. A solution file is a structure for organizing projects in Visual Studio.

How to add new file to solution explorer?

Adding FilesRight click the project or contained folder and choose Add | Existing Item... . Use Show All Files . Click on files or folders you would like to add to the project and choose Include In Project . Drag and drop files and folders from Windows Explorer.

How to add solution items Visual Studio?

Adding a Solution Item To add a new file as a solution item, start by right-clicking the solution's name in the Solution Explorer pane. Choose "Add" from the context-sensitive menu that appears.

How to add a new project to a solution in Visual Studio 2019?

Add a projectFrom the right-click or context menu of Solution 'QuickSolution' in Solution Explorer, select Add > New Project. A dialog box opens that says Add a new project. Enter the text empty into the search box at the top, and then select C# under Language.


2 Answers

Ok, I realised I could just record a Macro to capture the operation then examine the code in the VS Macro IDE.

The code required to do this is.

DTE.ItemOperations.AddExistingItem(filePath);
like image 60
Martyn Avatar answered Nov 15 '22 11:11

Martyn


To do this you need to access the ProjectItems member of the Project and call AddFromFile()

ProjectItem pi = project.ProjectItems.AddFromFile(filePath);
like image 45
the_mandrill Avatar answered Nov 15 '22 10:11

the_mandrill