Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Wednesday, May 16, 2012

How to get all items in current directory in C#

To get all items in a given current directory it needs to use a combination of two methods: GetDirectories(), GetFiles(). Both of them are the static method in class Directory which return all folders, and all files in the given directory respectively.
static String[] Dir(String path)
{
     // Get all folders in a given path
     List list = Directory.GetDirectories(path).ToList();
     // Get all files in a given path then add them to the list which contains folders
     list.AddRange(Directory.GetFiles(path));
     // You may sort the result, the ordering will be similar to dir function in the command prompt
     list.Sort();
     // Get the result
     return list.ToArray();
}
To use the function you written, it is very easy to use by giving the string path to it, it will give you an result.
static void Main(string[] args)
{
     string[] filepaths = Dir(@"C:\\");
     // Show all items under your drive C.
     foreach (String filepath in filepaths)
          Console.WriteLine(filepath);
}

No comments:

Post a Comment