Reputation: 4841
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 FileSystemInfo
s 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.
Upvotes: 0
Views: 1894
Reputation: 24336
Try something like this:
class MySweetObject{
HashSet fileInfoSet;
HashSet directoryInfoSet;
//Logic needed to manipulate files as you see fit
//Logic needed to access files as you see fit
}
Then write it as:
public MySweetObject GetDirectoryContentsRecursively (string path) { ... }
Create a custom object and pass that around to the caller.
Upvotes: 0
Reputation: 19230
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?
Upvotes: 1
Reputation: 17556
see below information of SortedSet if you are uisng .net 4.0
http://msdn.microsoft.com/en-us/library/dd412070.aspx
and Directory.Enumarate in .net 4.0 is desinged for the task you are doing.
Upvotes: 1