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
|// Replace all instances of < > with your variables|
|using (var context = new ClientContext(<siteUrl>))|
|context.Credentials = new SharePointOnlineCredentials(UserName, SecurePass);|
|listToOperate = context.Web.GetListByUrl(<listRelUrl>);|
|//Create the folder first|
|Folder folder = listToOperate.RootFolder.EnsureFolder(folderName);|
|//Setting the Metadata Defaults for the Folder|
|MetadataDefaults metadataDefaults = new MetadataDefaults(context, listToOperate);|
|metadataDefaults.SetFieldDefault(folder, "<ColumnName>", "-1;#" + <taxonomy values>);|
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 !!!