SharePoint Online - Supporting Special Characters

SharePoint Online has started supporting characters like ‘#’,’%’,’,’ in file names which can be uploaded to document libraries. Earlier these characters were not allowed. So, files can be referenced in CSOM using below lines of code,

  1. File newFile = extContext.Web.GetFileByServerRelativeUrl (docURL);  

Now, if the file has any of the supported special characters in it, then you will get the "file not found" error. So, a better way to get the reference to a file about whether it contains special characters or not is to use ResourcePath object.

You have to pass the file URL in decoded format. i.e. URLs as is.

  1. Uri ExternalUrl = new Uri(ExternalSiteURL);  
  2. string extToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, ExternalUrl.Authority, TokenHelper.GetRealmFromTargetUrl(ExternalUrl)).AccessToken;  
  3. using(ClientContext extContext = TokenHelper.GetClientContextWithAccessToken(ExternalUrl.AbsoluteUri, extToken))  
  4. {  
  5.     ResourcePath filePath = ResourcePath.FromDecodedUrl(docURLDecoded);  
  6.     File newFile = extContext.Web.GetFileByServerRelativePath(filePath);  
  7.     extContext.Load(newFile);  
  8.     extContext.ExecuteQuery();  
  9. }  

But if you intend to send email notification by forming HTML hyperlinks in email body containing URLs to the file containing these special characters then you might have to encode the document URLs using UrlPathEncode function available from SharePoint Utilities.

So, to encode file you need to use the below code:

  1. String docUrl = SP.Utilities.HttpUtility.UrlPathEncode(docUrl, false);