Cannot access SharePoint folder with special characters in the name using .Net and PnP Framework

RUSUMircea-4594 0 Reputation points
2025-03-28T20:52:41.4633333+00:00

Extracting files from SharePoint for Office 365 using PnP framework for .Net

This code used to work correctly for the past year, however It now started failing randomly with a "File not Found" error (actually folder not found):

Dim sDataFolder as String = "Reporting & Metrics"
Dim ctx As ClientContext = New PnP.Framework.AuthenticationManager(CLIENT_ID, cer, TENANT_ID).GetContext(sContext)
ctx.Load(ctx.Web)
ctx.ExecuteQuery()

Dim rootFolders As FolderCollection = ctx.Web.GetFolderByServerRelativeUrl(sDataFolder).Folders

ctx.Load(rootFolders, Function(folders1) folders1.Include(Function(f) f.ListItemAllFields))
ctx.ExecuteQuery() <— this line is generating a System.IO.FileNotFoundException

The issue seems to be related to character & present in folder name. We replaced it with %26:

Dim sDataFolder as String = "Reporting%20%26%20Metrics"

We still get this random error described above. Weird that sometime the code works without error!

All extractions from folders that don't contain special characters in the name are not affected.

Please advise

Microsoft 365 and Office SharePoint Development
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Emily Du-MSFT 51,836 Reputation points Microsoft External Staff
    2025-03-31T02:25:14.26+00:00

    This issue you are experiencing when accessing SharePoint folder contains special characters like ampersand "&" through PnP Framework for .NET, is known challenge. SharePoint imposes restrictions on certain characters in file and folder names, which can lead to unexpected errors when these characters are present.

    To ensure compatibility, consider renaming folders to eliminate special characters. For example, rename "Reporting & Metrics" to "Reporting and Metrics".

    If renaming is not feasible, ensure that special characters are properly URL-encoded in your code, the ampersand "&" should be encoded as "%26".

    When dealing with special characters, consider using GetFolderByServerRelativePath instead of GetFolderByServerRelativeUrl, as they handle special characters more effectively.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.