如何通过文件名查找ProjectItem

时间:2013-10-17 12:54:52

标签: c# .net visual-studio envdte

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

这是我对IVsSingleFileGenerator的生成方法的实现

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;
}

3 个答案:

答案 0 :(得分:7)

我正在使用这个用户友好的 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,作为新项目的指南。搜索并获取源代码..

答案 1 :(得分:0)

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

答案 2 :(得分:0)

可能会有点晚,但是请使用DTE2.Solution.FindProjectItem(fullPathofChangedFile);

相关问题