c# - Writing List<String> of Directories with Subdirectories -
now, know there lot of questions on stackoverflow folder recursion , getting folder including it's sub-directories etc. pp., haven't found related i'm encountering here.
my problem follows:
i've taken code snippet folder recursion here (page bottom) , adapted needs; is, having not write (sub)directories console having add them list instead. here code (note part that's commented out):
private static list<string> showallfoldersunder(string path) { var folderlist = new list<string>(); try { if ((file.getattributes(path) & fileattributes.reparsepoint) != fileattributes.reparsepoint) { foreach (string folder in directory.getdirectories(path)) { folderlist.add(folder); // console.writeline(folder); showallfoldersunder(folder); } } } catch (unauthorizedaccessexception) { } return folderlist; }
this how call (dir
string
containing path):
var _folders = showallfoldersunder(dir); foreach (string folder in _folders) { console.writeline(folder); }
the problem first level of folders added list, meaning output example:
[...] c:\users\test\pictures c:\users\test\recent c:\users\test\saved games c:\users\test\searches c:\users\test\sendto [...]
if uncomment console.writeline(folder);
method, echoes (sub)directories console:
[...] c:\users\test\appdata\roaming\microsoft\internet explorer\quick launch\user pinned c:\users\test\appdata\roaming\microsoft\internet explorer\quick launch\user pinned\implicitappshortcuts c:\users\test\appdata\roaming\microsoft\internet explorer\quick launch\user pinned\taskbar c:\users\test\appdata\roaming\microsoft\internet explorer\userdata c:\users\test\appdata\roaming\microsoft\internet explorer\userdata\low c:\users\test\appdata\roaming\microsoft\mmc c:\users\test\appdata\roaming\microsoft\network [...]
i'm desperate after having spent hours researching mistake. have clue what's causing problem?
modify method this
private static void showallfoldersunder(string path, list<string> folderlist) { try { if ((file.getattributes(path) & fileattributes.reparsepoint) != fileattributes.reparsepoint) { foreach (string folder in directory.getdirectories(path)) { folderlist.add(folder); // console.writeline(folder); showallfoldersunder(folder, folderlist); } } } catch (unauthorizedaccessexception) { } }
now call this
var _folders = new list<string>(); showallfoldersunder(dir, _folders);
this way prevent many list creation , memory consumption in other answers. using way supply initial list method , add entries it, other answers generate list each time , copy result upper list , cause lot of memory allocation, copy , deallocation.
Comments
Post a Comment