Saturday, November 5, 2011

Find all References to a Master Page or Page Layout in SharePoint

“This item cannot be deleted because it is still referenced by other pages” is a common error we get when we trying to delete a master page or page layout from the “Master pages and page layouts” gallery.
      

One of the ways to find all the references to a file in SharePoint is to use the "Site Content and Structure" page from the Site Actions menu, which is used to manage both the content and structure of the SharePoint site collection.

1. Go to “Site Actions” -> “Site Content and Structure” and select “Master Page Gallery”. 

2. Click on "Show Related Resources" on the toolbar.

3. Select the file you want to find all the references. All the related resources will be listed down with the location.

In addition to find file references, the “Site Content and Structure” page is a great way to copy or move files between libraries on different sites in a site collection. More information on how to work with Site Content and Structure can be found here.


If you are interested in getting all related resources of a file programmatically, we can do it by using BackwardLinks property and ForwardLinks property of SPListItem object.

using (SPSite site = new SPSite("http://prasad"))
{
   using (SPWeb web = site.OpenWeb())
   {
      // Get default.aspx
      SPFile file = web.GetFile("default.aspx");

      // Gets the URLs of all files that link to the current file from the current site collection. Pages that link to the current file from another Web site or site collection are not included in the backward link information.
      foreach (SPLink link in file.BackwardLinks)
      {
         Console.WriteLine(link.Url);
      }

      // Gets the URLs of all the links from the file to other pages, including internal links (to pages in the same Web site), and external links (to pages in other Web sites and site collections on the server).
      foreach (SPLink link in file.ForwardLinks)
      {
         Console.WriteLine(link.Url);
      }
   }
}

This code is not only applicable to Master pages and Page Layouts, but also applicable to Web Parts pages, items in a document libraries, and files in folders, as SPFile class represents a file in a SharePoint Web site that can be a Web Parts page, an item in a document library, or a file in a folder.

5 comments:

Anonymous said...

Thanks; this is just what I needed!

Anonymous said...

The "Show Related Resources" button really helped. Thanks!

Anonymous said...

Thank you very much. This helped a lot!

Unknown said...

It is incredible and informative knowledge. Impressive.
SharePoint Training Institutes in Hyderabad

artsikaj said...

Huge help with this post. Thanks a lot.