0
votes

I have a sharepoint document library containing documents and folders ( introduced as a new content type) and I'm having an event reciever on document added only to my folders so to retrieve the parent folder of my newly added document I tried to write this way but it doesn't seem to work well :

public override void ItemAdded(SPItemEventProperties properties)
{
    base.ItemAdded(properties);

    //getting the item (document) newly added to my content type folder
    SPListItem myItem = properties.ListItem;
    //getting the folder containing my doc
    SPFolder myFolder = myItem.File.ParentFolder;
    //other code on my SPFolder
}
2
Joy, could you accept some answer? - Milan Jaros

2 Answers

0
votes

This snippet from sharepoint.stackexchange helped me:

SPFile file = properties.ListItem.Web.GetFile(properties.ListItem.Url);
SPFolder fileFolder = file.ParentFolder;

https://sharepoint.stackexchange.com/questions/7090/get-containing-folder-list-for-spfile-item

0
votes

I use custom extension method:

SPFolder myFolder = myItem.GetParentFolder();
// TODO Test myFolder for null, because it could happen in edge cases

Where implementation is like:

public static SPFolder GetParentFolder(this SPListItem spListItem) 
{
    SPFolder parentFolder = null;
    // Try to get it from folder
    if (spListItem.Folder != null)
    {
        parentFolder = spListItem.Folder.ParentFolder;
    }
    // Try to get it from file
    else if (spListItem.File != null)
    {
        parentFolder = spListItem.File.ParentFolder;
    }
    // At last get file - it is more time/resource consuming
    else
    {
        SPFile spFile = spListItem.Web.GetFile(spListItem.Url);
        if (spFile != null)
            parentFolder = spFile.ParentFolder;
    }
    // Can be null
    return parentFolder;
}