Nesting Files in Visual Studio

A neat trick that I’ve used a few times to help organize files in a project is nest some under a related “master” file just like an aspx file and its code-behind.  I’ve mostly done this to group some page-specific JavaScript files with the page but also to group some partial classes for a WCF service together under a single “master” file.  This is hardly new (I think I did it for the first time with a project file from VS2008 and I know it has been around even longer than that) but every once in a while it comes up in a conversation so I thought it was worth sharing.

Grouping files in this manner is pretty straightforward but short of using an extension (we’ll look at that in a moment) there’s no way to group arbitrary files directly within Visual Studio.  That means that for this exercise we’ll be manually editing a project file.

Ungrouped Files

Ungrouped Files

Let’s assume that we have a Default.js file that we want to nest under Default.aspx.  To edit the project file I usually use the Edit Project File option included with the PowerCommands extension to streamline the Unload Project and Edit [project].csproj options.  Once the project file is open in the code editor we need to find Default.js.  Because Default.js is simply included content it will be in a <content> element like the following:

<Content Include="Default.js" />

Once we’ve located the element we need to insert a child DependentUpon element to identify Default.aspx its parent. You’ll probably see plenty of examples in the project file but our finished XML should look like this:

<Content Include="Default.js">
	<DependentUpon>Default.aspx</DependentUpon>
</Content>

Note: Check the Common MSBuild Project Items documentation on MSDN to see which elements DependentUpon can be applied to.

Grouped Files

Grouped Files

With the changes made, save the file and reload the project in the IDE. When the project loads Default.js should no longer appear in the main tree but instead be nested under Default.aspx.

If you’re not comfortable editing the project file directly there are some extensions that can streamline this process:

I haven’t tried either extension but they’re both highly rated in the gallery.  If you know of any others let me know and I’ll add them to the list.