How to rename a publishing page in code
-
16-10-2019 - |
Pergunta
I'm trying to do a bulk page rename (NB. the file name e.g. default.aspx, not the displayed title)
foreach (PublishingPage page in pweb.GetPublishingPages())
{
Console.WriteLine(page.Name);
page.Name = GetNewNamingConventionForPage(page.Name); //error, it's read only
}
What gives? I can rename it manually in the pages library.
Solução
You need to set the "FileLeafRef"
field of the underlying SPListItem
for the publishing page. You need to first check out the file (or create it and then Update it for new sites), update the .ListItem["FileLeafRef"]
property and then check it back in and publish it.
This code is to create a new publishing page and then change the file name. You have to run the .Update
on the PublishingPage before setting the FileLeafRef otherwise you get an "object does not exist"
error.
if (PublishingWeb.IsPublishingWeb(curWeb))
{
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(curWeb);
PublishingPage pubPage = pubWeb.AddPublishingPage();
pubPage.Title = "My New Page Title";
pubPage.Update();
pubPage.ListItem["FileLeafRef"] = "default"; //.aspx is added automatically
pubPage.ListItem.SystemUpdate(); //SystemUpdate doesn't update the modified fields
pubPage.CheckIn("");
pubPage.ListItem.File.Publish("");
}
Update: BaseName changed to FileLeafRef, BaseName is readonly and we can't update this field.
Outras dicas
Its beacuse PublishingPage.Name is a read-only property.
You could try:
page.ListItem("Name")
I have not tested this so do not know if this will do exactly what you need, but you definitely cannot set using the Name property.
var url = oldUrl.Replace(oldFileName, newFileName);
publPage.ListItem.File.MoveTo(url);