Skipper68
Skipper68

Reputation: 3

C# SharePoint get entire folder path my item is in

I know I can get the current folder the document is in but I need to get all of the folders up to the library level.

Document Library
**Folder1
****Folder2
******Folder3
*******Document

When I use properties.ListItem.File.ParentFolder.Name; on the "Document", it just gives me "Folder 3" What I'd like to eventually get is "Document Library\Folder1\Folder2\Folder3"

Thanks Cory,
I used your method and this is how I did it. I'd upvote but I don't have enough points...
string currentItemName = properties.ListItem.Name; string currentItemPath = properties.ListItem.Url; currentItemPath= currentItemPath.Replace(currentItemName, "");

Upvotes: 0

Views: 4310

Answers (2)

Servy
Servy

Reputation: 203814

We can start out creating a generic function to, when given a node in a tree, return a sequence of that node and all of its ancestors:

public static IEnumerable<T> GetAncestors<T>(
    this T node,
    Func<T, T> parentSelector)
{
    while (node != null)
    {
        yield return node;
        node = parentSelector(node);
    }
}

It's then as simple as passing the item's folder into this method along with a simple lambda to get that folder's parent:

var folder = item.Folder;
var allFolders = GetAncestors(folder, f => f.ParentFolder);

Upvotes: 0

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107528

I do this by capturing the relative URL of the file, which is just properties.ListItem.Url in your case. This might give you something like:

/Document Packages/Folder ABC/Document XYZ.doc

Then you can trim off everything after the last /.

Upvotes: 2

Related Questions