如何在VSIX项目的解决方案文件夹中获取项目
本文关键字:项目 文件夹 获取 解决方案 VSIX | 更新日期: 2023-09-27 18:00:03
嗨,我遇到了一个问题,在Visual Studio扩展中有一个自定义生成任务。我需要识别我的自定义项目类型的项目。如果它们在解决方案的根目录上,我可以做得很好,但当它在解决方案文件夹中时,问题就会出现。我可以将解决方案文件夹作为EnvDTE.Project获取,但不确定如何从该文件夹中获取项目。
我以为我可以从projects Collection属性中获得它,但这是空的。
如有任何协助,我们将不胜感激。
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
}
我通过更多的研究和一些试错来解决这个问题。如果其他人遇到这个问题,我将主代码更改为
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;
}
希望这能帮助其他人。
我在T4模板中遇到了一个类似的问题,我必须在解决方案中按名称查找任何级别的项目:根、文件夹、嵌套文件夹。
为了参考,我把它粘贴在这里。这完全基于@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;
}
#>