Question

I'm looking for a way to add a text file to a SharePoint list that DOESN'T enumerate the entire file set. According to this SharePoint best practices article, you shouldn't access the SPList.Files property because it enumerates the entire collection. Unless you actually want every item, then it's very inefficient. All I want to do is add a single text file to the root folder of a SharePoint list. So far I'm using the following:

using (MemoryStream stream = new MemoryStream())
   {
       StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);

       // write some stuff to the stream ...
       // create a file-name-safe URL ...
       // create a SPFileCollectionAddParameters object ...   

       // add the file
       SPFile newFile = loggingList.RootFolder.Files.Add(fileURL, stream, addProperties);  

}

So, is enumerating SPList.RootFolder.Files the same as SPList.Files, in this case (since there is only a root folder with text files) and if so, is there a way to add a single file without enumerating the file collection?

Thanks in advance. :D

Was it helpful?

Solution

Actually there's nothing wrong with calling Files.Add. Simply accessing the member will not enumerate the collection. If you were to call GetEnumerator() on it or use it in a foreach loop, that would trigger the enumeration.

OTHER TIPS

Being afraid to use SPList.Items (similar to SPList.Files, but used in simple lists, not document libraries), we created a helper function that returns an empty collection, hence NOT fetching all items from the server:

public static SPListItemCollection CreateEmptyCollection(SPList List)
 {
   const string EmptyQuery = "0";
   SPQuery q = new SPQuery {Query = EmptyQuery};
   return List.GetItems(q);
 }

Then, when adding items to a list, we do it like this:

ListItem = CreateEmptyCollection(someList).Add("/sites/somesite/lists/somelist/path/to/required/folder", SPFileSystemObjectType.File, "");

Thanks naivists. You have reminded that I once saw an article that suggested the same thing but as an extension method on SPList:

public static SPListItem AddItemOptimized(this SPList list, string folderUrl, 
        SPFileSystemObjectType underlyingObjectType, string leafName)
    {
        const string EmptyQuery = "0";
        SPQuery q = new SPQuery
        {
            Query = EmptyQuery
        };
        return list.GetItems(q).Add(folderUrl, underlyingObjectType,leafName);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top