public void AddFile(TemplateInfo template) { if (_applicationObject.SelectedItems.Count == 1) { var selectedItem = _applicationObject.SelectedItems.Item(1); string targetPath = null; Project project = selectedItem.Project ?? (selectedItem.ProjectItem != null ? selectedItem.ProjectItem.ContainingProject : null); if (selectedItem.ProjectItem == null) { if (project != null) { // project is selected, add it to the top level of the project targetPath = (string)project.Properties.Item("FullPath").Value; } } else { // an item within the project is probably selected object parent = selectedItem.ProjectItem; while (parent != null && !_acceptableTargets.Contains(GetKind(parent))) { parent = GetParent(parent); } if (parent != null) { if (parent is ProjectItem) { targetPath = (string)((ProjectItem)parent).Properties.Item("FullPath").Value; } else if (parent is Project) { targetPath = (string)((Project)parent).Properties.Item("FullPath").Value; } } } if (!String.IsNullOrEmpty(targetPath)) { string path = Path.Combine(targetPath, template.BaseName + (String.IsNullOrEmpty(template.Extention) ? "" : ("." + template.Extention))); int i = 1; while (File.Exists(path)) { path = Path.Combine(targetPath, template.BaseName + i++ + (String.IsNullOrEmpty(template.Extention) ? "" : ("." + template.Extention))); } string ns = null; try { ns = (string)project.Properties.Item("DefaultNamespace").Value; } catch(ArgumentException) { // probably a 'web site' project. Determine namespace from the website name instead. ns = project.FullName.TrimEnd('\\'); ns = ns.Split('\\').Last() ?? "Namespace"; } File.WriteAllText(path, template.GetContent(ns, Path.GetFileNameWithoutExtension(path))); var newItem = project.ProjectItems.AddFromFile(path); // make it selected in solution explorer _applicationObject.ToolWindows.SolutionExplorer.GetItem(GetSolutionPath(newItem, true)).Select(vsUISelectionType.vsUISelectionTypeSelect); // now start renaming it to the user can give it a proper name _applicationObject.ExecuteCommand("File.Rename"); } else { MessageBox.Show("Unable to locate folder to add the item to."); } } }