Login

How do I search and replace the contents of a property on multiple pages?

Versions: 4.70, FAQ number: 44, Old FAQ number: 935

Q: How do I search and replace the contents of a property on multiple pages?

A: See example code below.

 

// Search and replace contents of a property in multiple pages.
// The following code should be added somewhere in an aspx.cs file.
 
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAccess;
 
 
// Example of a search and replace of contents in a string property.
private void SearchAndReplaceInProperty(string propertyName,
                                        string searchText,
                                        string replaceWith)
{
   PropertyCriteriaCollection criterias = new PropertyCriteriaCollection();
   PropertyCriteria criteria;
   PageDataCollection matchingPages;
   int currentSid = EPiServer.Security.UnifiedPrincipal.CurrentSid;
   string propertyValue;
 
   // Define start page for search (here we search the entire site)
   PageReference startPage = Global.EPConfig.RootPage;
 
   // Setup criterias to search for text in a property
   criteria = new EPiServer.PropertyCriteria();
   criteria.Type = PropertyDataType.LongString;
   criteria.Name = propertyName;
   criteria.Value = searchText;
   criteria.StringCondition = EPiServer.Filters.StringCompareMethod.Contained;
   // Use criteria.Condition = EPiServer.Filters.CompareCondition.Equal 
   // if you want to search for numeric values.

   criterias.Add(criteria);
 
   matchingPages =
      Global.EPDataFactory.FindPagesWithCriteria(startPage, criterias);
 
   Response.Write(String.Format("Found {0} matching page(s).<br><br>",
                                matchingPages.Count));
 
   foreach(PageData page in matchingPages)
   {
      propertyValue = page.Property[propertyName].ToString();

      page.Property[propertyName].Value = 
         propertyValue.Replace(searchText, replaceWith);
 
      EPiServer.Global.EPDataFactory.Save(page, SaveAction.Publish);
 
      Response.Write(String.Format("Page modified: {0} ({1})<br>",
                                   page.PageName, page.PageLink.ID));
   }
}

 

EPiTrace logger