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,
- 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.
- Uri ExternalUrl = new Uri(ExternalSiteURL);
- string extToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, ExternalUrl.Authority, TokenHelper.GetRealmFromTargetUrl(ExternalUrl)).AccessToken;
- using(ClientContext extContext = TokenHelper.GetClientContextWithAccessToken(ExternalUrl.AbsoluteUri, extToken))
- {
- ResourcePath filePath = ResourcePath.FromDecodedUrl(docURLDecoded);
- File newFile = extContext.Web.GetFileByServerRelativePath(filePath);
- extContext.Load(newFile);
- extContext.ExecuteQuery();
- }
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:
- String docUrl = SP.Utilities.HttpUtility.UrlPathEncode(docUrl, false);