Search code examples
c#.net-4.0typesfilesystemsdirectory-structure

Directory tree data type?


What would be the return type of the following method? (T)

public T GetDirectoryContentsRecursively (string path) { ... }

The method will read the contents of a remote directory, and read the contents of each sub-directory and each of that object's sub-directories and so on.

I have thought about using List<object>, where object could be another List<object> etc... but I don't want the caller to have to be casting everything into FileSystemInfos every time they want to use the method.

Every file must be a FileInfo and every directory a DirectoryInfo, both of which inherit the abstract class FileSystemInfo.

I just can't figure out what data type is best used to represent this.

Any ideas? Do I need to make my own DirectoryTree type?

Edit: The data is to be fetched from a server, probably directory by directory, one at a time. What I need to do is take this data and reconstruct it into something that I can pass to the user. This means I can't just pass a DirectoryInfo, then call its GetFileSystemInfos() because the Directory will not exist on the local machine.


Solution

  • I think maybe the approach is wrong, what are you trying to achieve with a tree structure that you can't by using the APIs directory as and when you need to?

    If the intention is to just walk the folder/file structure on the remote directory then you don't necessary need to build your own in-memory representation to do this. If you are rendering the structure, just grab the top level, and load other levels on demand.

    If you really want to go down this route then you could just return IEnumerable<string> with all the directory and file paths. DirectoryInfo and FileInfo are relatively expensive objects. It all depends on purpose, can you give any more info?