Return an enumerable collection of directory names in a specified path using LINQ in CSharp

Description

The following code shows how to return an enumerable collection of directory names in a specified path using LINQ.

Example


using System;/*from w  w  w.  j  a  v a 2s .c  om*/
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{

    private static void Main(string[] args)
    {
        try
        {
            string dirPath = "c:\\";

            // LINQ query.
            var dirs = from dir in Directory.EnumerateDirectories(dirPath)
                       select dir;

            // Show results.
            foreach (var dir in dirs)
            {
                // Remove path information from string.
                Console.WriteLine("{0}", 
                    dir.Substring(dir.LastIndexOf("\\") + 1));

            }
            Console.WriteLine("{0} directories found.", dirs.Count<string>().ToString());
        }
        catch (UnauthorizedAccessException UAEx)
        {
            Console.WriteLine(UAEx.Message);
        }
        catch (PathTooLongException PathEx)
        {
            Console.WriteLine(PathEx.Message);
        }
    }
}




















Home »
  C# Tutorial »
    IO »




File Attribute
File Security
Directory Attribute
Directory Recursive
Binary File
Text Field
Buffered IO
Create Copy Delete Move
CSV
Drive
File System Watcher
Isolated Storage
MemoryStream
Serialize
Zip