bradgonesurfing
bradgonesurfing

Reputation: 32162

Enumerate all files in current visual studio project

I'm trying to write a simple Visual Studio 2012 extension. I have generated the extension template and can bring up a dialog box from a tool menu.

I'd like to enumerate all files in the currently open project and then filter them according to some rules. What I'm looking for is a code snippet to return IEnumerable. FileHandle should have the following interface or something similar.

interface IFileHandle {
        // Return the string 
        string Path;
        // Open the file in the editor
        void OpenEditorFor();
}

FYI I'm trying to build a fuzzy file finder for visual studio. The current file search is less than suitable as you have to have exact match. I can handle writing the indexer and the fuzzy searcher but the interface to Visual Studio extension writing is a bit cryptic at the moment.

Upvotes: 2

Views: 4002

Answers (1)

bradgonesurfing
bradgonesurfing

Reputation: 32162

This seems to be the simple answer. In the context of a visual studio extension will return all files.

public IEnumerable<ProjectItem> Recurse(ProjectItems i)
{
    if (i!=null)
    {
        foreach (ProjectItem j in i)
        {
            foreach (ProjectItem k in Recurse(j))
            {
                yield return k;
            }
        }

    }
}
public IEnumerable<ProjectItem> Recurse(ProjectItem i)
{
    yield return i;
    foreach (ProjectItem j in Recurse(i.ProjectItems ))
    {
        yield return j;
    }
}

public IEnumerable<ProjectItem> SolutionFiles()
{
    Solution2 soln = (Solution2)_applicationObject.Solution;
    foreach (Project project in soln.Projects)
    {
        foreach (ProjectItem item in Recurse(project.ProjectItems))
        {
            yield return item;
        }
    }
}

You can then do neat tricks with it like implement the search function at the core of my CommandT clone.

private static string Pattern(string src)
{
    return ".*" + String.Join(".*", src.ToCharArray());
}

private static bool RMatch(string src, string dest)
{
    try
    {
        return Regex.Match(dest, Pattern(src), RegexOptions.IgnoreCase).Success;
    }
    catch (Exception e)
    {
        return false;
    }
}

private static List<string> RSearch(
string word,
IEnumerable<string> wordList,
double fuzzyness)
{
    // Tests have prove that the !LINQ-variant is about 3 times
    // faster!
    List<string> foundWords =
        (
            from s in wordList
            where RMatch(word, s) == true
            orderby s.Length ascending 
            select s
        ).ToList();

    return foundWords;
}

which is used like

var list = RSearch("bnd", SolutionFiles().Select(x=>x.Name))

Upvotes: 9

Related Questions