How to Set a Property Bag Key as an Indexed (Queriable via Search) Programmatically using C# Client Side Object Model (CSOM)

Sathish Nadarajan
SharePoint MVP
Published On :   30 Mar 2017
Visit Count
Today :  1    Total :   2052

Recently in our projects, we are using a lot of Property Bag Values. But in some specific requirement, we were trying to Search the Property Bag from the SharePoint Keyword Query. To do that, we want the Property Bag Key to be Indexed as Queryable. That, we need to do programmatically as part of our Provisioning. Let us see, how to do that. The code is very straight forward.

Basically, we are updating a Property Bag called vti_indexedpropertykeys with the values Encoded.

 namespace Console.Office365
     using Microsoft.SharePoint.Client;
     using OfficeDevPnP.Core;
     using System;
     using System.Linq;
     class Program
         static void Main(string[] args)
             AuthenticationManager authManager = new AuthenticationManager();
             var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant("https://***", "Sathish@******.com", "**********");
             Web web = clientContext.Web;
             PropertyValues properties = clientContext.Web.AllProperties;
             // Get the Existing Property Bag Values from the Indexxed Property Keys
             var oldPropertyBagValue = clientContext.Web.PropertyBagContainsKey("vti_indexedpropertykeys") ? Convert.ToString(properties["vti_indexedpropertykeys"]) : string.Empty;
             string[] O365Properties = new string[] { "PropertyBagKey1", "PropertyBagKey2", "PropertyBagKey3"};
             string newPropertyBagValue = string.Empty;
             // Get the New Property Bag Values.  In our case, it is propertybagkey1, propertybagkey2 etc., 
             foreach (var propertiesString in O365Properties)
                 newPropertyBagValue += Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(propertiesString)) + "|";
             // Add the new values to the existing ones.
             newPropertyBagValue = oldPropertyBagValue + newPropertyBagValue;
             // take the Unique Items.  There could be changes that a key can be repeated.  So always using Distinct.
             var distinctNewPropertyBagValue = newPropertyBagValue.Split('|').Distinct().ToArray();
             // Update the Property Bag Key
             properties["vti_indexedpropertykeys"] = string.Join("|", distinctNewPropertyBagValue).Trim();

Happy Coding,

Sathish Nadarajan.