I was investigating a bug in the SharePoint app I’m working on where a function was failing on sites with URLs containing spaces. Although I’m not a fan of creating sites with spaces in the URL, SharePoint lets you do it so it’s going to happen. At first, I thought the issue would be easy to track down and that the problem had something to do with how we were parsing a URL somewhere. It took a bit of time, but I eventually found out that SharePoint is a bit quirky about what it allows in URLs. Ultimately, the issue boiled down to this:
So if you have a server-relative URL like /sites/Some Site With Spaces/ but you pass the URL encoded version /sites/Some%20Site%20With%20Spaces/ to the OpenWeb method, then you are going to end up with a File Not Found error.
One of the reasons you may be getting this error is if you are using the Uri.AbsolutePath property to retrieve the server-relative URL of your web. The AbsolutePath property automatically URL encodes spaces. To avoid this issue, you can just use the Uri.LocalPath property, which returns spaces in all of their unencoded glory.
If you are not using a Uri then you can just replace all of the occurrences of %20 with a space in the string and you’ll be good to go.