Show the List of Drives in the TreeView Control-ASP.NET

You can see the code that uses the static GeTDrives method of the DriveInfo class to get a list of all installed drives, then iterates through them. For each fixed, formatted, and available (ready) drive, the code creates a new node containing details of the drive. It then sets the ImageUrl to the custom image, specifies that clicking this node will cause a postback that executes the “populate on demand” event handler, and adds the node to the treeView.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TreeView.aspx.cs" Inherits="TreeView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
   <title>Untitled Page</title>
   <form id="form1" runat="server">
           <asp:TreeView ID="treeDir" runat="Server">
           <asp:Label ID="lblError" runat="Server"></asp:Label>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

public partial class TreeView : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    private void CreateTreeView()
        TreeNode node = new TreeNode("My Computer", "Root");
        node.SelectAction = TreeNodeSelectAction.None;
        node.Expanded = true;
            // get a list of installed drives
            DriveInfo[] allDrives = DriveInfo.GetDrives();
            foreach (DriveInfo d in allDrives)
                // only include fixed drives that are ready
                if (d.DriveType == DriveType.Fixed && d.IsReady)
                    // create text for the TreeView to display
                    StringBuilder sb = new StringBuilder();
                    sb.Append(d.Name.Substring(0, 2));
                    sb.Append(" ");
                    sb.Append(" (");
                    sb.Append(") ");
                    Double space = d.AvailableFreeSpace / 1024 / 1024;
                    sb.Append(" MB available");
                    String theName = sb.ToString();
                    String theValue = d.Name;
                    // add a node to the TreeView with "drive" image
                    TreeNode child = new TreeNode(theName, theValue);
                    child.ImageUrl = "images/icon_drive.gif";
                    // specify postback for populating child nodes
                    child.SelectAction = TreeNodeSelectAction.Expand;
                    child.PopulateOnDemand = true;
        catch (Exception ex)
            lblError.Text = "ERROR: " + ex.Message + "<p />";

Next Post Previous Post
No Comment
Add Comment
comment url