September 25, 2010

List files and pictures in directories using C#

It is quite simple to list all files in a directory in C# using the System.IO.Directory class. This class contains the GetFiles(string path) method that returns all filenames as a string array within the path specified. It also contains the overloaded GetFiles(string path, string match) method that returns all filenames in a string array in the path and criteria (match) specified.

In the following example, I have demonstrated how to get all files in a directory and how to get all pictures from a particular directory.

Code Snippet
  1. public class DirectoryListing
  2. {
  3.     string path = @"C:\Users\shahed.kazi\Desktop";
  4.  
  5.     //Get all files in desktop
  6.     public string[] GetAllFiles()
  7.     {
  8.         return Directory.GetFiles(path);
  9.     }
  10.  
  11.     //Get pictures from desktop
  12.     public string[] GetAllPictures()
  13.     {
  14.         List<string[]> list = new List<string[]>();
  15.         list.Add(Directory.GetFiles(path, "*.bmp"));
  16.         list.Add(Directory.GetFiles(path, "*.png"));
  17.         list.Add(Directory.GetFiles(path, "*.gif"));
  18.         list.Add(Directory.GetFiles(path, "*.jpg"));
  19.         list.Add(Directory.GetFiles(path, "*.jpeg"));
  20.  
  21.  
  22.         List<string> filename = new List<string>();
  23.  
  24.         for (int i = 0; i < list.Count; i++)
  25.         {
  26.             foreach (string s in list[i])
  27.                 filename.Add(s);
  28.         }
  29.         return filename.ToArray();
  30.     }
  31. }

0 comments:

Reference: Shahed Kazi at AspNetify.com