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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With