In this article, we are going to see the steps to create an index to a SharePoint field using C#. Indexing is a data structure which is used to quickly locate and access the data in the database table. The Client-Side Object Model (CSOM) is used internally for these operations.
Why Indexed columns?
- Indexed columns allow fast retrieval.
- It improves the performance of the database.
- It reduces the disc access while performing the query.
Step 1
Open Visual Studio, go to File -> New -> and select Project.
Step 2
In Templates select Visual C#, select Console App (.Net Framework) and giveappropriate name in name text box and then click ok button
Step 3
Step 4
Open the program.cs file and type the below code
Program.cs
- using System;
- using System.Collections.Generic;
- using Microsoft.SharePoint.Client;
- namespace SPField_Indexing {
- class Program {
- static void Main(string[] args) {
- try {
- SPHelper sphelper = new SPHelper();
- string url = "", userName = "", password = "";
- Console.WriteLine("Please enter site url:");
- url = Console.ReadLine();
- Console.WriteLine("Please enter username:");
- userName = Console.ReadLine();
- Console.WriteLine("Please enter password:");
- password = Console.ReadLine();
- if (url != null && userName != null && password != null) {
- sphelper.doIndexing(url, userName, password);
- }
- } catch (Exception) {
- throw;
- }
- }
- }
- class SPHelper {
- public void doIndexing(string SiteUrl, string UserName, string Password) {
- OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
- using(var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(SiteUrl, UserName, Password)) {
- if (clientContext != null) {
-
- string listName = "HubflyTeam";
-
- List < string > FieldName = new List < string > () {
- "NameHF",
- "LocationHF"
- };
- List list = clientContext.Web.Lists.GetByTitle(listName);
- clientContext.Load(list);
- clientContext.ExecuteQuery();
- foreach(string fields in FieldName) {
- Field field = list.Fields.GetByTitle(fields);
- field.Indexed = true;
- field.Update();
- clientContext.ExecuteQuery();
- }
- Console.WriteLine("SharePoint Field Indexed Successfully!");
- Console.ReadLine();
- }
- }
- }
- }
- }
Step 5
Run the project using the F5 function key. Enter the Site URL, Username and Password to access the SharePoint Site,
Step 6
Open the list setting like the below Snapshot.
Drag down and click Indexed columns like the below snapshot,
That's it, SharePoint Field has been indexed successfully.
Thus, you have seen steps to create SharePoint field index programmatically using C# code. Feel free to fill up the comment box below if you need any assistance.