如何通过文件名查找ProjectItem

问题描述 投票:12回答:2

我正在为Visual Studio开发自定义工具。该工具已分配给文件,在文件更改时,我收到了该文件的名称,并且应该在项目中生成一些更改。我需要通过接收的文件名找到一个ProjectItem。我发现只有一个解决方案,它枚举该解决方案的每个项目中的所有项目。但这似乎是一个巨大的解决方案。有没有一种方法可以通过文件名获取项目项而无需枚举?

这是我对IVsSingleFileGenerator的Generate方法的实现

public int Generate(string sourceFilePath, string sourceFileContent, string defaultNamespace, IntPtr[] outputFileContents, out uint output, IVsGeneratorProgress generateProgress)
{
    var dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));

    ProjectItem projectItem = null;

    foreach (Project project in dte.Solution.Projects)
    {
        foreach (ProjectItem item in project.ProjectItems)
        {
            var path = item.Properties.Item("FullPath").Value;
            if (sourceFilePath.Equals(path, StringComparison.OrdinalIgnoreCase))
            {
                projectItem = item;
            }
        }               
    }

    output = 0;
    outputFileContents[0] = IntPtr.Zero;

    return Microsoft.VisualStudio.VSConstants.S_OK;
}
c# .net visual-studio envdte
2个回答
8
投票

我也使用DTE的用户友好世界来创建指导。我没有找到更好的解决方案。基本上这些是我正在使用的方法:

迭代项目:

public static ProjectItem FindSolutionItemByName(DTE dte, string name, bool recursive)
{
    ProjectItem projectItem = null;
    foreach (Project project in dte.Solution.Projects)
    {
        projectItem = FindProjectItemInProject(project, name, recursive);

        if (projectItem != null)
        {
            break;
        }
    }
    return projectItem;
}

查找单个项目:

public static ProjectItem FindProjectItemInProject(Project project, string name, bool recursive)
{
    ProjectItem projectItem = null;

    if (project.Kind != Constants.vsProjectKindSolutionItems)
    {
        if (project.ProjectItems != null && project.ProjectItems.Count > 0)
        {
            projectItem = DteHelper.FindItemByName(project.ProjectItems, name, recursive);
        }
    }
    else
    {
        // if solution folder, one of its ProjectItems might be a real project
        foreach (ProjectItem item in project.ProjectItems)
        {
            Project realProject = item.Object as Project;

            if (realProject != null)
            {
                projectItem = FindProjectItemInProject(realProject, name, recursive);

                if (projectItem != null)
                {
                    break;
                }
            }
        }
    }

    return projectItem;
}

我使用的代码片段较多,可以找到here,作为新项目的指南。搜索并获取源代码。


0
投票

要获取project.documents-查找项目-使用Linq查询文件

© www.soinside.com 2019 - 2024. All rights reserved.