Posts Tagged ‘Files’


The below method fetches the path for all the files present in a Directory or Sub Directory under the parent Directory.
The file path are fetched in a list of string to be used for any implementation as and when required.


private List DirSearch(string sDir)
{
List files = new List();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
//throw ex
}

return files;
}


Below is the simple method that can be used to fetch file names of all the file present under a File Directory.


private static string[] GetFileNames(string path, string filter)
{
string[] files = Directory.GetFiles(path, filter);
for (int i = 0; i < files.Length; i++)
files[i] = Path.GetFileName(files[i]);
return files;
}

This code is designed in such a way so that we can obtain filename according to filetype.
If I provide ‘*.*’ as an input to filter, all the file names will be obtained in string array, but if I obtain ‘*.jpg’ as an input the string array will contain file names for all ‘.jpg’ files.

Example:

string[] fileNames = GetFileNames(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");