April 16, 2024

SamTech 365

PowerPlatform, Power Apps, Power Automate, PVA, SharePoint, C#, .Net, SQL, Azure News, Tips ….etc

Retrieve SPFile object by full URL

It may be assumed that you need to pass separate strings when opening a SPSite / SPWeb / SPFile (leading to all kinds of nasty url string chopping to determine base URL /site URL/ file name) when actually you can do this instead (this may be well known to many, but an experienced SharePoint guy I spoke to recently was not aware of it so I thought it would be worth posting)

Helpfully the SPSite constructor doesn’t care about the library name , filename or the .docx suffix and will just open http://server/site for you. Then use the default constructor for OpenWeb() as we’ve already passed the full URL. Then use SPWeb.GetFile(), which takes the full URL. Easy, and no strings were harmed during the process.

1
2
3
4
5
6
7
8
9
10
11
using(SPSite site = new SPSite(url))
{
    using(SPWeb web = site.OpenWeb()) 
    {
        SPFile file = web.GetFile(url);
    }
}

It may be assumed that you need to pass separate strings when opening a SPSite / SPWeb / SPFile (leading to all kinds of nasty url string chopping to determine base URL /site URL/ file name) when actually you can do this instead (this may be well known to many, but an experienced SharePoint guy I spoke to recently was not aware of it so I thought it would be worth posting)

Helpfully the SPSite constructor doesn’t care about the library name , filename or the .docx suffix and will just open http://server/site for you. Then use the default constructor for OpenWeb() as we’ve already passed the full URL. Then use SPWeb.GetFile(), which takes the full URL. Easy, and no strings were harmed during the process.

1
2
3
4
5
6
7
8
9
10
11
using(SPSite site = new SPSite(url))
{
    using(SPWeb web = site.OpenWeb()) 
    {
        SPFile file = web.GetFile(url);
    }
}