This code will display the directories and files in the particular drive in the tree view like windows explorer but I add to display size of the directory and file in the tree. I used D:\ is the default drive to make a tree, but you can change the drive as you like.Recursion used for display and calculating the sub directories and their files.
I used the System.IO namesspace and DirectoryInfo and FileInfo classes and its members GetDirectories() GetFiles() for manage the files and directories. The FileInfo.Length Property used to get the size of the file. TreeView control used for make tree.
This code give the Drive name as input and make root node...
private void Form1_Load(object sender, EventArgs e) { DirectoryInfo dirinfo = new DirectoryInfo(@"D:\"); \\ default drive TreeNode root = new TreeNode(dirinfo.FullName ); \\ make root node treeView1.Nodes.Add(root); long size = GetDir(root,dirinfo); }
This cod list the directories and files and calculate the size
private static long GetDir(TreeNode tree ,DirectoryInfo dirpath) { long totalsize=0; TreeNode rootnode = tree ; FileInfo[] fileinfos = dirpath.GetFiles(); foreach (FileInfo fileinfo in fileinfos) { String str1,str2; str1 = fileinfo.Name ; str2 = str1 + "==>" + fileinfo.Length +" bytes" ; rootnode.Nodes.Add(str2 ); totalsize += fileinfo.Length;
} DirectoryInfo dirlist = new DirectoryInfo(tree.FullPath ); DirectoryInfo[] tempdir = dirlist.GetDirectories(); foreach (DirectoryInfo dir in tempdir) { rootnode = new TreeNode(dir.Name ); tree.Nodes.Add(rootnode ); totalsize += GetDir(rootnode, dir); } return totalsize; }
You Should add TreeView Control in the window form before use this code. The only contraints is some system wont allow to access the System Volume Information folder and system folders that will throw the exception.. You will give the access permission to access that drive and system folders. Thanks Best regards Lingesh
AttachmentsTree of Files and directory with Size (21804-14344-drivelist.txt)
|
| Author: pandikumar 14 Oct 2008 | Member Level: Bronze Points : 0 |
Nice.... its worked... Its look like simple explorer.
|
| Author: Roopesh Babu Valluru 14 Oct 2008 | Member Level: Gold Points : 0 |
good article man...thx a lot for this...
|