I have a Document Library called "x" with file named "y". I am curious what the best way to get the SPFile object for the specified SPListItem. Currently I am using this:


I don't like using [0] to get the SPListItem... interested in reccomendations


  • Not sure what you are trying to achieve, but Items[0] will just get you the first item in the list.
    – Louis
    Commented Jun 29, 2012 at 5:59

3 Answers 3


You can use the SPWeb GetFile method to retrive the SPFile located at a specified url. Try something like this:

SPFile file = SPContext.Current.Web.GetFile(string.Format("{0}/{1}", x, y));

Blockquote I don't like using [0] to get the SPListItem...interested in reccomendations

Well, SPList.Items[0] syntax fetch ALL THE DATA from SharePoint and after - give you item by index. That's a common behavior.

You might use also SPList.GetItemById or similar methods or even make a caml query against the target list w/ SPList.GetItems method. It's up to your particular situation and it would b nice if you can describe it.

SPContext.Current.Web.GetFile method is also ok, it really depends on your situation.


Did some more searching and found this as the answer...LINQ to the rescue.

        SPList csvList = SPContext.Current.Web.Lists[libraryName];

        SPFile file = csvList.Items.Cast<SPListItem>()
                                   .Where(x => x.Name.Equals(fileName))
                                   .Select(x => x.File)
  • Note that SPWeb.Lists[libraryName] and SPList.Items incur significant performance costs for large lists. Should be avoided in general as best practice. You should be using GetFile() as Rich suggests
    – Louis
    Commented Jun 29, 2012 at 5:58
  • Good point...in this instance the list will always be very small. Which part of this solution in particular incurs the performance hit?
    – MikeC
    Commented Jun 29, 2012 at 15:07
  • Using the string index SPWeb.Lists[string ListName], behind the scenes the API fetches metadata for all lists and then a for loop to find a matching name. With [Guid] or [index] it fetches directly the corresponding list.
    – Louis
    Commented Jun 29, 2012 at 16:04
  • Same for SPList.Items, your LINQ query will fetch all items and loop through them to execute the Where(). Using a targeted CAML query is better, or in your case GetFile directly.
    – Louis
    Commented Jun 29, 2012 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.