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)
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);
}
}


STRING SEARCH USING REGEX METHOD IN C#
ReplyDeleteHow 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