Friday, August 21, 2009

Opening SPFile from full file URL

I had to implement a custom search to find documents matching certain criteria. I could easily find a document and retrieve its "Path" (full url). From this URL, I needed to get the associated SPFile object. This took longer then I thought it warranted.

Here is the solution:

string fileUrl = dt.Rows[0]["Path"].ToString();
 
using (SPSite site = new SPSite(fileUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPFile file = web.GetFile(fileUrl);
 
        if (!file.Exists)
            throw new ApplicationException("Could not find document");
 
        return file;
    }
}

No comments: