在项目目录中以编程方式创建项目项

本文关键字:项目 方式 创建 编程 | 更新日期: 2023-09-27 18:17:19

我正试图以编程方式创建一个项目项。我有这个代码

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

但是我想在项目内的指定目录中创建项目(这会在项目的根目录中创建项目)。这可能吗?谢谢你的帮助!

在项目目录中以编程方式创建项目项

这就是我如何添加我的cpp文件,在你的情况下应该没有什么不同。

代码将在项目中的"SourceFiles'SomeFolder"下以及项目视图树中的"SourceFiles"文件夹中添加文件(它应该已经存在了)。

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);

请不要期望代码可以立即编译并运行-这里没有执行一些无效状态检查。