When you need to retrieve all the files from specific directory, here is the one of the effective sample that will retrieve all the “JPEG” files which using less memory compare to conventional way.
Code
// Create stack instance
static Stack directoryStack = new Stack();
static void Main(string[] args)
{
Console.WriteLine("Application to find all the JPG files");
Console.WriteLine("=====================================");
Console.Write("Location:");
string location = Console.ReadLine();
// Delete file.txt
if (File.Exists(@"C:\file.txt"))
File.Delete(@"C:\file.txt");
// Create DirectoryInfo instance
DirectoryInfo di = new DirectoryInfo(location);
// Add valid DirectoryInfo instance into stack
if (di != null)
directoryStack.Push(di);
// stop looping when directoryStack items is equal to 0
while (directoryStack.Count != 0)
GetFiles();
Console.WriteLine("Success");
Console.ReadLine();
}
// Get and write all the "JPEG" files
static void GetFiles()
{
StreamWriter sw = System.IO.File.AppendText(@"C:\file.txt");
// Get latest Directory Information from stack
DirectoryInfo currentDirectory = directoryStack.Pop();
// Get all sub directories
DirectoryInfo[] getDirectories = currentDirectory.GetDirectories();
// Add all sub directories into stack
for (int i = 0; i < getDirectories.Length; i++)
directoryStack.Push(getDirectories[i]);
// Get all jpg files
FileInfo[] getFilesInfo = currentDirectory.GetFiles("*.jpg");
// Write jpg full details into file.txt
for (int j = 0; j < getFilesInfo.Length; j++)
sw.WriteLine(getFilesInfo[j].FullName);
sw.Close();
}
Download full script file: Load_files_using_stack.cs
You also can using .NET library to search files that allocated within the directory and subdirectories.
code
string searchLocation = @"C:\Program Files\";
// Get directory information
DirectoryInfo searchDirectory = new DirectoryInfo(searchLocation);
// Get all the "JPEG" within directory and it's subdirectories
FileInfo[] getFiles = searchDirectory.GetFiles("*.jpg", SearchOption.AllDirectories);
// Retrieve all match files information
for (int i = 0; i < getFiles.Length; i++)
Console.WriteLine(getFiles[i].FullName);
Console.ReadLine();