Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if an SPListItem is a document or a folder

I have a loop that is looping through a document library like in the example below.

foreach (SPListItem item in DocumentLibrary)
{
}

How do I tell if the SPListItem is a document or a folder?

like image 509
Joe Avatar asked Jul 08 '11 11:07

Joe


3 Answers

The Folder property of the list item will be null if the item is not a folder, so you can write:

public bool IsFolder(SPListItem item)
{
    return item.Folder != null;
}

In the same way, the File property of the item will be null if the item is not a document. However, the documentation advises against using this property in that case:

The File property also returns null if the item is a folder, or if the item is not located in a document library, although it is not recommended that you call this property in these cases.

An alternate way is to check the BaseType property of the list:

public bool IsDocument(SPListItem item)
{
    return !IsFolder(item)
        && item.ParentList.BaseType == SPBaseType.DocumentLibrary;
}
like image 100
Frédéric Hamidi Avatar answered Nov 18 '22 15:11

Frédéric Hamidi


Use SPFileSystemObjectType enumeration. Here's a sample...

foreach (SPListItem item in docLib.Items)
{
    if (item.FileSystemObjectType == SPFileSystemObjectType.Folder)
    {
        // item is a folder 
        ...
    }
    else if (item.FileSystemObjectType == SPFileSystemObjectType.File)
    {
        // item is a file
        ...
    }
}
like image 23
Sudipta Mukherjee Avatar answered Nov 18 '22 16:11

Sudipta Mukherjee


if( item["ContentType"].ToString() == "Folder")
like image 2
Pertinent Info Avatar answered Nov 18 '22 16:11

Pertinent Info