February 25, 2014

So, I have got an asp.net application and I can see the file structure of the application using Visual Studio or by navigating to the folder and viewing the directories but how can I view it on the server's end. This is not particularly useful and I don't recommend having this on the server but it might be useful for debugging specially when you don't have full control on deployment.

Since, I am getting the file structure of an asp.net application, I will use a web control for displaying the file structure. Because of the type of data I am expecting to get, a TreeView control is the perfect control to bind this data to. The TreeView control is instantiated like below.

<asp:TreeView ID="tview" runat="server"></asp:TreeView>

 

Now, I will need to get the list of all directories and files and bind to this TreeView. To start with, I will need to get the root application folder as discussed in my previous post – how to get root application path.

Next, I have written a method that will recursively go through all the directories and add the file names and directory names with the TreeView. And finally, from Page_Load event, I have added the nodes to the TreeView. Here is the code for how it works.

Create Nodes
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     tview.Nodes.Clear();
  4.     tview.Nodes.Add(CreateNodes(new DirectoryInfo(RootDirectory())));
  5. }
  6.  
  7. //return root directory
  8. private string RootDirectory()
  9. {
  10.     return Server.MapPath("~");
  11. }
  12.  
  13. //recursively bind TreeView to directory structure
  14. private TreeNode CreateNodes(DirectoryInfo di)
  15. {
  16.     var dirNode = new TreeNode(di.Name);
  17.  
  18.     foreach (var dir in di.GetDirectories())
  19.         dirNode.ChildNodes.Add(CreateNodes(dir));
  20.     foreach (var file in di.GetFiles())
  21.         dirNode.ChildNodes.Add(new TreeNode(file.Name));
  22.     return dirNode;
  23. }

 

Once the page is run, the following screen shot is displayed for my application.

image

0 comments:

Reference: Shahed Kazi at AspNetify.com