File: App_Code/AutoSiteMapProvider.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Caching;
namespace MyNamespace
{
public class AutoSiteMapProvider : StaticSiteMapProvider
{
private SiteMapNode _rootNode;
private static List<string> _excluded = new List<string>();
private List<string> _dependencies = new List<string>();
static AutoSiteMapProvider()
{
_excluded.Add("app_code");
_excluded.Add("app_data");
_excluded.Add("app_themes");
_excluded.Add("bin");
}
protected override SiteMapNode GetRootNodeCore()
{
return BuildSiteMap();
}
public override SiteMapNode BuildSiteMap()
{
lock (this)
{
HttpContext context = HttpContext.Current;
_rootNode = (SiteMapNode)context.Cache["RootNode"];
if (_rootNode == null)
{
Clear();
string folderUrl = HttpRuntime.AppDomainAppVirtualPath;
string defaultUrl = folderUrl + "/Default.aspx";
_rootNode = new SiteMapNode(this, folderUrl, defaultUrl, "Home");
AddNode(_rootNode);
AddChildNodes(_rootNode);
_dependencies.Add(HttpRuntime.AppDomainAppPath);
CacheDependency fileDependency = new CacheDependency(_dependencies.ToArray());
context.Cache.Insert("RootNode", _rootNode, fileDependency);
}
return _rootNode;
}
}
private void AddChildNodes(SiteMapNode parentNode)
{
AddChildFolders(parentNode);
AddChildPages(parentNode);
}
private void AddChildFolders(SiteMapNode parentNode)
{
HttpContext context = HttpContext.Current;
string parentFolderPath = context.Server.MapPath(parentNode.Key);
DirectoryInfo folderInfo = new DirectoryInfo(parentFolderPath);
DirectoryInfo[] folders = folderInfo.GetDirectories();
foreach (DirectoryInfo folder in folders)
{
if (!_excluded.Contains(folder.Name.ToLower()))
{
string folderUrl = parentNode.Key + "/" + folder.Name;
SiteMapNode folderNode = new SiteMapNode(this, folderUrl, null, GetName(folder.Name));
AddNode(folderNode, parentNode);
AddChildNodes(folderNode);
_dependencies.Add(folder.FullName);
}
}
}
private void AddChildPages(SiteMapNode parentNode)
{
HttpContext context = HttpContext.Current;
string parentFolderPath = context.Server.MapPath(parentNode.Key);
DirectoryInfo folderInfo = new DirectoryInfo(parentFolderPath);
FileInfo[] pages = folderInfo.GetFiles("*.aspx");
foreach (FileInfo page in pages)
{
if (!_excluded.Contains(page.Name.ToLower()))
{
string pageUrl = parentNode.Key + "/" + page.Name;
if (String.Compare(pageUrl, _rootNode.Url, true) !=0)
{ SiteMapNode pageNode = new SiteMapNode(this, pageUrl, pageUrl, GetName(page.Name));
AddNode(pageNode, parentNode);
}
}
}
}
private string GetName(string name)
{
name = Path.GetFileNameWithoutExtension(name);
return name.Replace("_", " ");
}
}
}
File: Web.Config
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<system.web>
<siteMap defaultProvider="MyAutoSiteMapProvider">
<providers>
<add
name="MyAutoSiteMapProvider"
type="MyNamespace.AutoSiteMapProvider" />
</providers>
</siteMap>
</system.web>
</configuration>