How to find list of files in a directory in Csharp – A tutorial
In many cases you need to read the file names in a directory to be able to process or take some action to process the files. Here is a simple program that will list out the files in a directory.
using System;
using System.IO;
class Program
{
static void Main()
{
// Put all file names in root directory into array.
string WorkingDirectory = @"C:\Users\abhinsv\Desktop\Imageresize_src\";
string[] array1 = Directory.GetFiles(WorkingDirectory,"*.jpg");
Console.WriteLine("--- List of the Files: ---");
foreach (string name in array1)
{
Console.WriteLine(name);
}
Console.ReadLine();
}
}
Pay special attention to
Directory.GetFiles(WorkingDirectory,”*.jpg”);
It will list out all the files in the directory with the extension jpg. If you wish to list all files, irrespective of the extension, you may use
Directory.GetFiles(WorkingDirectory);
It will list all files with in the directory WITH path. Here is a typical output
--- List of the Files: ---
C:\Users\abhinsv\Desktop\Imageresize_src\imageresize_horiz.jpg
C:\Users\abhinsv\Desktop\Imageresize_src\imageresize_vert.jpg
If you want to list only the names of the file, you can use
Console.WriteLine(Path.GetFileName(name));
in place of
Console.WriteLine(name);
This will, for example give the following output
--- List of the Files: ---
imageresize_horiz.jpg
imageresize_vert.jpg
If you are uninitiated, you may like to take CSharp Tutorial.
Related posts: