13

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?

Joe
  • 531
  • 2
  • 7
  • 16

6 Answers6

14

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;
}
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
7

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
        ...
    }
}
user3750325
  • 1,502
  • 1
  • 18
  • 37
2
if (item.Folder!=null) 
  // item is Folder and Folder will hold the SPFolder class
Flexo
  • 87,323
  • 22
  • 191
  • 272
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
  • 1
    Correct answer 7 minutes earlier! +0. Life is unfair!!! ;) Just kidding +1 to you too. – Lzh Jan 23 '14 at 10:34
2
if( item["ContentType"].ToString() == "Folder")
Flexo
  • 87,323
  • 22
  • 191
  • 272
Pertinent Info
  • 135
  • 4
  • 15
1

I think the safest way is to check the FileSystemObjectType property

Rob Windsor
  • 6,744
  • 1
  • 21
  • 26
0
if (oitem.ContentType.Name == spWeb.AvailableContentTypes[SPBuiltInContentTypeId.Folder].Name)
                        {
                            Console.WriteLine("Folder Name: " + oitem.Name.ToString());
                        }
MAK
  • 129
  • 1
  • 8