locked
I dont understeand why AddFromTemplate returns null . RRS feed

  • Question

  • Let me first ask one issue in my code. 

      DTE2 dte2 = ServiceProvider.GetService(typeof(DTE)) as DTE2;
                Solution2 solution2 = dte2.Solution as Solution2;
                string projectName = "MyProject4";
                string projectFullPath =  System.IO.Path.GetDirectoryName(solution2.FullName) +@"\"+ projectName;
                string templatePath = solution2.GetProjectTemplate("ConsoleApplication.zip", "CSharp");
                Project destProject = solution2.AddFromTemplate(templatePath, projectFullPath, projectName, false);

                string itemName = "View.cs";
                string itemTemplatePath = solution2.GetProjectItemTemplate("CodeFile", "CSharp");
                if (destProject == null)
                    throw new ArgumentNullException("destProject should not be null");

                destProject.ProjectItems.AddFromTemplate(itemTemplatePath, itemName);

    When I executed the above code, I could see the project was created successfully. 

    the problem is, however, the Project instance obtained from AddFromTemplate was null. 

    I don't understand this situation. can you explain why the project instance(destProject) is null, 

    and how can I fix it?

    Friday, May 18, 2018 1:17 AM

All replies

  • Per the documentation, this always returns a NULL.

    The reason is that a template may produce multiple items, or multiple projects. Once upon a time (many versions back), this worked. But when support for multiple items/projects was added, the original developers opted not to revise the underlying COM automation interfaces, and instead opted to just start returning NULL.

    There are other ways to find the project or item just added. For example, you can search the collection of Projects (DTE.Solution.Projects), or if you implement a custom IWizard, your IWizard.ProjectFinishedGeneration() will be passed the EnvDTE.Project.

    Sincerely,


    Ed Dore

    Sunday, May 20, 2018 3:55 AM