Labels

slider

Recent

Navigation

List all directories and sub-directories

list all directories and subdirectories windows, list all directories and subdirectories c#, directories in c#

Introduction

To list directories and sub-directories in c#, Namespace: using System.IO is used.
We often need to list directories and sub-directories when we writing program in C#. This program shows how we can list directories, sub-directories, files in c#.
Namespace: using System.IO;
Assembly:  mscorlib (in mscorlib.dll)
Directories-subdirectories-in-C#


Specify Path:

string folderpath = @"E:\TechnologyCrowds\Myfolder\\";
Here we can provide folder path where we have to list all files under this path:

Loop to access files Under Folder:

// here accessing file name one by one
foreach (string file in files)
{
    string name = Path.GetFileName(file);
}

Handle Unauthorized Access Exception:

This code handles unauthorized access call, throw specific message to end user.

Handle Path Long Exception:

This code handles long path exception, if user pass long path then it will throw exact exception.


catch (PathTooLongException PathEx)
{
    Console.WriteLine(PathEx.Message);
}

Here is written complete Program to list files under directories in C#:

Private void getdirs()
{
   try
   {
       string filepath = string.Empty;
       // Folder path
       string folderpath = @"E:\Anjan_Profile\PTS\\";

       // First checking directory exists or not
       if ((Directory.Exists(@"E:\Anjan_Profile\PTS\")))
       {
  // fetching directory files
  string[] files = Directory.GetFiles(folderpath, "*.*");

  // here accessing file name one by one
  foreach (string file in files)
  {
      string name = Path.GetFileName(file);
  }
       }
   }
   catch (UnauthorizedAccessException UAEx)
   {
       Console.WriteLine(UAEx.Message);
   }
   catch (PathTooLongException PathEx)
   {
       Console.WriteLine(PathEx.Message);
   }
}

Summary

Share

Anjan kant

Outstanding journey in Microsoft Technologies (ASP.Net, C#, SQL Programming, WPF, Silverlight, WCF etc.), client side technologies AngularJS, KnockoutJS, Javascript, Ajax Calls, Json and Hybrid apps etc. I love to devote free time in writing, blogging, social networking and adventurous life

Post A Comment:

1 comments:

  1. STRING SEARCH USING REGEX METHOD IN C#
    How to validate an Email by Regular Expression?
    string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
    if (Regex.IsMatch(Email, EmailPattern, RegexOptions.IgnoreCase))
    {
    Console.WriteLine("Email: {0} is valid.", Email);
    }
    else
    {
    Console.WriteLine("Email: {0} is not valid.", Email);
    }

    Use Reference String.Regex() Method http://imaginationhunt.blogspot.in/2015/07/string-search-using-regex-method-in-c.html

    ReplyDelete