How to list all ProjectItems in Project

If you’re looping through the project items (Project.ProjectItems) hoping to get a list of all the files at the root – you’re probably going to be dissapointed, because you’ll be missing all the code-behind files.
Turns out the code-behind files are in turn ProjectItems of a top-level file.
So basically if you want to get a list of all files in a (root directory of a) project, you need to check if the physical files (ProjectItem.Kind = {6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}) have a non-null ProjectItems property,
and pull those in as well.

This is the code I’ve used:

// project is of type Project here, but it could be a ProjectItem too.
List<ProjectItem> pli = project.ProjectItems.ToList<ProjectItem>();
List<ProjectItem> pfiles = pli.Where(x => x.GetKind() == ProjectItemKinds.PhysicalFile && x.ProjectItems.Count > 0).ToList();
foreach (var item in pfiles)
{
    pli.AddRange(item.ProjectItems.ToList<ProjectItem>());
}

Keep in mind it’s using extension methods of my own, but it’ll give the idea.

Leave a Reply

Your email address will not be published. Required fields are marked *