Listing Files & Folders in a directory

Listing all files in a specified folder

The code below shows how to use the System.IO.DirectoryInfo function to retreive all the files in the specified location, it also show how to get the extension and size aswell. You will have to parse a folder location such as c:\ to the parameter Location. You need one listview1 control

//FIND ALL FILES IN FOLDER
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Location);
foreach (System.IO.FileInfo f in dir.GetFiles("*.*"))
   {
   //LOAD FILES
   ListViewItem lSingleItem = listView1.Items.Add(f.Name);
   //SUB ITEMS
   lSingleItem.SubItems.Add(Convert.ToString(f.Length));
   lSingleItem.SubItems.Add(f.Extension);
   }

Listing all folders in a specified folder

This example is similer to the above file routine, but uses dir.GetDirectories to find the folders. In this example you need one treeView control.

//FIND ALL FOLDERS IN FOLDER
TreeNode Main =  treeView1.Nodes.Add("Folders in: " + Location);
Main.Tag = "";
   foreach (System.IO.DirectoryInfo g in dir.GetDirectories())
       {    
       //LOAD FOLDERS
       TreeNode MainNext = Main.Nodes.Add(g.FullName);
       MainNext.Tag = (g.FullName);
       }

You might also like...

Comments

Colin Harman MACITP I am 26 and live in sydney, australia. I enjoy drinking and going out, but I also enjoy writing programs + creating websites in my free time. I play golf and ski. One of my main intrests whe...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.” - Antoine de Saint Exupéry