Inspired by Marek's post on modifying existing pages I decided to complement my post on programmatically publishing new pages with a post on how to modify and publish existing pages in EPiServer.
1. Why you can't modify a PageData object
As Marek points out in his post, EPiServer will always return read-only versions of PageData objects for performance:
//Retrieve a read-only version of a page
PageReference myPageRef = new PageReference(1);
PageData myPage = DataFactory.Instance.GetPage(myPageRef);
Derived methods for fetching pages yield the same result, such as the GetChildren() method. So, we would get an exception if we tried this:
myPage.PageName = "My modified page"; //Exception thrown
This is because it is much faster for EPiServer to fetch read-only versions from the database or page cache. So, we need a different approach in order to modify our existing pages.
2. Get a writable page version to edit
Before we can modify and re-publish an existing page we need to get a writable version of the page. This is accomplished by calling the CreateWritableClone() method of a PageData object:
//Get a writable PageData object to modify
PageData myWritablePage = myPage.CreateWritableClone();
Now we can edit the values of our page properties:
Property["MainBody"].Value =
"<p>This content was updated.</p>";
3. Publish your modified page
Once we've updated our page properties we can save and publish the new page through code by calling the Save method of the DataFactory class:
//Perform 'Save and publish' programmatically
DataFactory.Instance.Save(myWritablePage, SaveAction.Publish);
Make sure to also check out my post on creating a page programmatically!