I have the following code which gives me a Stack containing the folder hierarchy of a path:
var path = @"C:\Folder1\Folder2\Folder3\Folder4\Folder5\FileName.ext";
// String array with an element for each level
var folders = path.Split('\\');
var stack = new Stack<string>();
foreach(var folder in folders)
stack.Push(folder);
var filename = stack.Pop(); // 'FileName.ext'
var parent = stack.Pop(); // 'Folder5'
var grandParent = stack.Pop(); // 'Folder4'
Just out of curiosity, is there a more elegant way to convert the folders array into a Stack without the foreach loop? Something like the (non-existent) following:
var folders = path.Split('\\').Reverse().ToStack();
I look forward to your suggestions!
Stack<T>has a constructor that acceptsIEnumerable<T>