您好我有一个问题,在Visual Studio扩展中有一个自定义生成任务。我需要识别我的自定义项目类型的项目。如果它们位于解决方案的根目录下,我可以做到这一点,但是当它在解决方案文件夹中时会出现问题。我可以将解决方案文件夹作为EnvDTE.Project获取,但我不确定如何从该文件夹中获取项目。
我以为我可以从项目Collection属性中获取它,但这是null。
非常感谢任何协助。
if (Scope == EnvDTE.vsBuildScope.vsBuildScopeSolution)
{
DTE2 dte2 = Package.GetGlobalService(typeof(EnvDTE.DTE)) as DTE2;
var sol = dte2.Solution;
EnvDTE.DTE t = dte2.DTE;
var x = t.Solution.Projects;
foreach(var proj in x)
{
try
{
var project = proj as EnvDTE.Project;
var guid = GetProjectTypeGuids(project);
if (guid.Contains("FOLDERGUID"))
{
//here is where I would get the project from the folder
}
答案 0 :(得分:14)
我设法通过更多的研究和一些反复试验来解决这个问题。如果有其他人提出这个问题,我将主要代码更改为
if (Scope == EnvDTE.vsBuildScope.vsBuildScopeSolution)
{
errorListProvider.Tasks.Clear();
DTE2 dte2 = Package.GetGlobalService(typeof(DTE)) as DTE2;
var sol = dte2.Solution;
var projs = sol.Projects;
foreach(var proj in sol)
{
var project = proj as Project;
if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
{
var innerProjects = GetSolutionFolderProjects(project);
foreach(var innerProject in innerProjects)
{
//carry out actions here.
}
}
}
}
GetSolutionFolderForProjects的代码是
private IEnumerable<Project> GetSolutionFolderProjects(Project project)
{
List<Project> projects = new List<Project>();
var y = (project.ProjectItems as ProjectItems).Count;
for(var i = 1; i <= y; i++)
{
var x = project.ProjectItems.Item(i).SubProject;
var subProject = x as Project;
if (subProject != null)
{
//Carried out work and added projects as appropriate
}
}
return projects;
}
希望这有助于其他人。
答案 1 :(得分:1)
我在T4模板中有一个类似的问题,我必须在解决方案中的任何级别找到一个名称的项目:root,folder,nested folder。
供参考,我在这里粘贴它。它完全基于@DaveGreen的解决方案,因此归功于他:
<#@ import namespace="System.Linq" #>
<#
var dte = (DTE)hostServiceProvider.GetService(typeof(DTE));
var project = GetProject(dte.Solution, "ProjectName");
#>
<#+
public static Project GetProject(Solution solution, string name)
{
var project = GetProject(solution.Projects.OfType<Project>(), name);
if (project == null)
{
throw new Exception($"Project {name} not found in solution");
}
return project;
}
public static Project GetProject(IEnumerable<Project> projects, string name)
{
foreach (Project project in projects)
{
var projectName = project.Name;
if (projectName == name)
{
return project;
}
else if (project.Kind == EnvDTE80.ProjectKinds.vsProjectKindSolutionFolder)
{
var subProjects = project
.ProjectItems
.OfType<ProjectItem>()
.Where(item => item.SubProject != null)
.Select(item => item.SubProject);
var projectInFolder = GetProject(subProjects, name);
if (projectInFolder != null)
{
return projectInFolder;
}
}
}
return null;
}
#>