Friday, April 8, 2022

Create folders with special characters in Sharepoint Online programmatically via CSOM

If you worked with SP on-prem you probably know that some special characters are not allowed in folders names there. In Sharepoint Online however it is possible to use some special characters in folders names:

How to create such folders with special characters programmatically via CSOM? If we will try to do it using the same approach which we used for SP on-prem it will implicitly remove all parts in folder names which come after special characters i.e. in above example abc, def, ghi:

public static ListItem AddFolder(ClientContext ctx, List list, string parentFolderUrl, string folderName)
{
    var lici = new ListItemCreationInformation
    {
        UnderlyingObjectType = FileSystemObjectType.Folder,
        LeafName = folderName.Trim(),
        FolderUrl = parentFolderUrl
    };

    var folder = list.AddItem(lici);
    folder["Title"] = lici.LeafName;
    folder.Update();
    ctx.ExecuteQueryRetry();

    return folder;
}

If we want to create folders with special characters we need to use another CSOM method Folder.AddSubFolderUsingPath:

public static void AddFolderUsingPath(ClientContext ctx, Folder parentFolder, string folderName)
{
    parentFolder.AddSubFolderUsingPath(ResourcePath.FromDecodedUrl(folderName));
    ctx.ExecuteQueryRetry();
}

With this method folders with special characters will be created successfully in Sharepoint Online.

No comments:

Post a Comment