Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio: Programmatically Create Project Items in project directory

I am trying to create a project item programmatically. i have this code

            string itemPath = currentSolution.GetProjectItemTemplate("ScreenTemplate.zip", "csproj");
        currentSolution.Projects.Item(1).ProjectItems.AddFromTemplate(itemPath, name);
        currentSolution.Projects.Item(1).Save();

But I would like to create the item in a specified directory inside the project (this creates the item in the root of the project). Is it possible? Thanks for help!

like image 266
Vlatom Avatar asked Jun 05 '13 19:06

Vlatom


1 Answers

That's roughly how I add my cpp file, should be no different in your case.

The code will add the file under "SourceFiles\SomeFolder" in the project and also in the "Source Files" folder in the project view tree (it should be already there).

Project project = null; // you should get the project from the solution or as active project or somehow else
string fileName = "myFileName.cpp";
string fileRelativePath = "SourceFiles\\SomeFolder\\" + fileName;

// First see if the file is already there and delete it (to create an empty one)
string fileFullPath = Path.GetDirectoryName(project.FileName) + "\\" + fileRelativePath;
if (File.Exists(fileFullPath))
    File.Delete(fileFullPath);

// m_applicationObject here is DTE2 or DTE2
string templatePath = (m_applicationObject.Solution as Solution2).ProjectItemsTemplatePath(project.Kind);

ProjectItem folderItem = project.ProjectItems.Item("Source Files");
ProjectItem myFileItem = folderItem.ProjectItems.AddFromTemplate(templatePath + "/newc++file.cpp", fileRelativePath);

Please don't expect the code to compile straight away and run - some checks for invalid state aren't performed here.

like image 70
Sergey Avatar answered Sep 21 '22 14:09

Sergey