这就是我添加我的 cpp 文件的大致方式,在你的情况下应该没有什么不同。
该代码将在项目的“SourceFiles\SomeFolder”下添加文件,并在项目视图树的“Source Files”文件夹中添加文件(它应该已经存在)。
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);
请不要指望代码会立即编译并运行——这里不会执行一些无效状态检查。