One of the coolest functionality of SharePoint libraries is able to set custom metadata default values for folders. What it means is that when users drop a file into a folder, the metadata values of the file will be automatically set based on those set on the folder level.
However, if you have got about 50-100 folders then it becomes a tedious task to do. So, we could do it programmatically through SharePoint CSOM. Below is a quick snippet of code to set it using SharePoint CSOM where I am setting a taxonomy field default values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.SharePoint.Client; | |
using Microsoft.SharePoint.Client.DocumentManagement; | |
// Replace all instances of < > with your variables | |
using (var context = new ClientContext(<siteUrl>)) | |
{ | |
context.Credentials = new SharePointOnlineCredentials(UserName, SecurePass); | |
listToOperate = context.Web.GetListByUrl(<listRelUrl>); | |
context.Load(listToOperate); | |
context.ExecuteQuery(); | |
//Create the folder first | |
Folder folder = listToOperate.RootFolder.EnsureFolder(folderName); | |
context.ExecuteQueryRetry(5); | |
//Setting the Metadata Defaults for the Folder | |
MetadataDefaults metadataDefaults = new MetadataDefaults(context, listToOperate); | |
metadataDefaults.SetFieldDefault(folder, "<ColumnName>", "-1;#" + <taxonomy values>); | |
metadataDefaults.Update(); | |
listToOperate.Update(); | |
context.ExecuteQuery(); | |
} |
Workaround for Azure Function TimeOut issue for Large number of folders
If you are using Azure Function, then you would hit the limit of function timeout (i.e. 10 minutes) while setting metadata for many folders such as 600 of them. So to overcome this limitation, you could use client_locationBasedDefaults.html override to set the metadata values directly. But please be aware that it might also corrupt the library if the above metadata setting up step is not done as below. The steps in this case would be
- Create a Test Folder
- Set the metadata values programmatically using the above process
- Delete the folder
- Override the client_locationBasedDefaults.html in the Forms folder of the library
So using the above steps, you could set metadata values for Folders in SharePoint libraries programmatically.
Happy Coding !!!
Hi Asish, great post!.. I tried the csom code but “metadataDefaults” is undefined. How did you initialise this variable?
LikeLike
Sorry Jason, I forgot to add the code for metadata defaults update. Have added it now. Please check.
LikeLike
I Still do not see the code, could you please provide that? It will be really helpful.
LikeLike
hey Prashant, sorry what part of the code is missing. Could you please point that. I can provide it?
LikeLike