Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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:

SPContext.Current.Web.Lists["x"].Items[0].File

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

TIA

share|improve this question
    
Not sure what you are trying to achieve, but Items[0] will just get you the first item in the list. –  Louis Jun 29 '12 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));
share|improve this answer

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.

share|improve this answer
up vote 0 down vote accepted

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)
                                   .First();
share|improve this answer
    
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 Jun 29 '12 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 Jun 29 '12 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 Jun 29 '12 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 Jun 29 '12 at 16:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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