c#: create filetree

Status
Not open for further replies.

office politics

It's all just 1s and 0s
Messages
6,555
Location
in the lab
I'm having trouble creating a file tree. I made notes on how to list files without recursion; see below. I'm not too keen on making on making objects. I think I want an object with string and a array that will hold the next level of objects. The node is the parent folder. The array is the subfolders and files. The object will contain a method that adds a object to it array.

I tried using the following code to make the object, but there's prolly something seriously wrong here.

Code:
private class FileTree {
        private string node;
        private List<FileTree> = new List<FileTree>;
    }


Notes:
Code:
filetree

  node - string

  childs - array of filetree

  AddChild(item); - create new filetree with item as node


list files - returns filetree

  create a stack of folders to check

  add server path

  do
    pop server path off the stack

    get directory listing of server path - return array (list of files & folders)

    add each list item as child to serverpath

      AddChild(serverpath + listString);      

    push folder server paths onto stack 

  while stack.count > 0
 
There are a few issues here. First, the fields in the FileTree class are private -- and they should be. However, you'll need to create public properties or methods to allow access to them from outside the class.

Second, the List<FileTree> field does not have a name. The compiler will catch that error when you try building the project, so that one won't go unnoticed for long.

Third, it would be beneficial for you to create a constructor that takes the 'node' as a parameter.

With all that said, I think it may be easier to understand if you change the names of some of the items in your code. Think of any item in the file system directory structure as a node because that's a good conceptual model. Here's a skeleton class called Node written in C# 3.0 (previous versions do not support automatic properties) with a convenience property for determining if the node is a file or folder:
Code:
class Node
{
	public Node(string path)
	{
		if (System.IO.Directory.Exists(path))
		{
			this.IsFolder = true;	
			this.Children = new List<Node>();
		}
		else if (!System.IO.File.Exists(path))
			throw new IOException("File or directory does not exist.");
			
		this.Path = path;
	}
	
	public List<Node> Children { get; private set; }
	
	public bool IsFolder { get; private set; }
	
	public string Path { get; private set; }
}

You could add more logic to populate the node's children internally, but it appears that you want to do that externally. I don't know that one way is really better than the other without knowing exactly how you're intending to use it. Regardless, either way will work.
 
Status
Not open for further replies.
Back
Top Bottom