I have a list that contains folders.
Using c# and object model, how can I see if the folder contains any items, or return a collection of all the items in that folder.
I have a list that contains folders.
Using c# and object model, how can I see if the folder contains any items, or return a collection of all the items in that folder.
Try the following code to get the items based on the folder,
using(SPSite site = new SPSite("site url"))
{
using(SPWeb web = site.OpenWeb())
{
SPFolder folder = web.GetFolder("/Docs/folder1");
if(folder.ItemCount > 0)
{
SPList list = web.Lists.TryGetList("ListName");
SPQuery query = new SPQuery();
query.Folder = folder;
SPListItemCollection listitem = list.GetItems(query);
}
}
}
SPListItemCollection = list.GetItems(query);
is typing error? And using TryGetList
is meaningless because you don't check later if list != null
. So if list doesn't exist your code will throw exception - same if you used web.Lists["ListName"]
.
Sep 21, 2011 at 13:17
You need to use SPQuery Class and define SPQuery.Folder Property
foreach (SPFolder folder in list.Folders) {
if (folder.ItemCount > 0) {
foreach (SPFile file in folder.Files) {
SPListItem item = file.Item;
// Do stuff with your item here.
}
foreach (SPFolder subfolder in folder.SubFolders) {
// Do stuff with your folder here.
// Think about perhaps using recursion if you want to list the items from this folder and beyond
}
}
}
Because we're using foreach, we don't really need to check if the itemcount is more than 0. But this is just an example to allow you to identify which folders have items and how you can access them
SPFile
is also wrong if you don't want to change content of file. @soniiic please read Best Practices: Common Coding Issues When Using the SharePoint Object Model
Sep 21, 2011 at 11:16