Sun. May 24th, 2020

Samir Daoudi's Technical Blog

SharePoint, Office 365, C#, .Net, SQL Server News, Tips, Ebooks, Events, Webinars ….etc

Retrieve SPFile object by full URL

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 etFile(), which takes the full URL string url = "http://server/site/documentlibrary/testdoc.docx";

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);
    }
}

Leave a comment

Copyright © All rights reserved. | Newsphere by AF themes.
Show Buttons
Hide Buttons

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.