I have code as part of an event receiver that creates a publishing page upon feature activation. That publishing page is built on a page layout that is deployed as part of that same feature.

The pages.Add method of the PublishingPage object requires a PageLayout object of the layout you wish to have the page created with. I'm currently using the following code to identify and set the PageLayout object.

PublishingWeb activePublishingWeb = PublishingWeb.GetPublishingWeb(web);
PublishingPageCollection pages = activePublishingWeb.GetPublishingPages();
PageLayout customLayout = null;
foreach (PageLayout layout in activePublishingWeb.GetAvailablePageLayouts())
    if (layout.Name.Equals("MyLayout.aspx", StringComparison.InvariantCultureIgnoreCase))
        customLayout = layout;

This method of grabbing all of the page layouts and iterating through them works, but it seems rather inefficient. Is there a better way to specifically target a page layout using a name or a URL? I know you can filter the PageLayout return by associated content type, but that still gives me a collection of all Welcome Pages, not just my custom one.

Any suggestions are appreciated!

With Per's suggestion below, here's the new code for anyone that may stumble upon this thread in the future:

SPFile customLayoutFile = web.GetFile("_catalogs/masterpage/MyLayout.aspx");
SPListItem customLayoutItem = customLayoutFile.Item;
PageLayout customLayout = new PageLayout(customLayoutItem);

If you have the url of the PageLayout you can use SPWeb.GetFile(url) to get the corresponding SPFile and the use the PageLayout constructor on the Item property of that SPFile

| improve this answer | |
  • That did it; thank you Sir! Original post updated with new solution. – webdes03 Oct 22 '12 at 18:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.