Sometimes you need the absolute URL of a file in SharePoint, and if you happen to just have the absolute URL then you are in luck. I suppose, however, that if you already have the absolute URL then you wouldn’t be here reading about how to to get it. It’s more likely that you have a File object reference and have noticed that SharePoint provides you with the ServerRelativeUrl property, conveniently leaving you with about half of what you need to get the job done.
There are two ways to get the absolute URL. The first is using a hidden list item field called FileRef. This approach works with any file as long as it is in a document library. Why? Because to get the FileRef value you have to go through the file’s backing ListItem, and system files that reside outside of document libraries do not have backing list items. So the following code will fail if attempted on a system file:
NOTE: this code works most of the time
1 2 3 4 |
var file = context.Web.GetFileByServerRelativeUrl( "/sites/Site/Library/MyFile.txt"); context.Load(file, f => f.ListItemAllFields["FileRef"]); context.ExecuteQuery(); var absoluteUrl = file.ListItemAllFields["FileRef"]; |
But what if you want a way that works for system files as well as for files that are in a document library? As much as I like to give SharePoint grief for not giving you everything you need in a nicely packaged format, all of the information is actually available if you know how to string it together (pun definitely intended). When you have a server relative URL to a file, it’s fairly easy to build the absolute URL to a file using the following code:
NOTE: this code works ALL of the time and may avoid a round-trip to SharePoint depending on your situation.
1 2 |
var serverRelativeUrl = "/sites/Site/Library/MyFile.txt"; var absoluteUrl = new Uri(context.Url) .GetLeftPart(UriPartial.Authority) + serverRelativeUrl; |
You just grab the missing authority information directly from the context’s URL property and slap the server relative URL on the end of it creating an absolute URL. Another nice aspect about this approach is if you already have the server relative URL, then this saves you an entire round-trip to SharePoint to acquire the absolute URL.
Load comments