To demonstrate the example first we will create a folder and add some files. For example, please check the below image.
Now for this article we will create a new .NET core console application. After creating files and folders we will add the below code.
string folderPath = "D:\\Projects\\Demo";
Console.WriteLine("Start Reading Files");
if (Path.Exists(folderPath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
var fileList = directoryInfo.GetFiles();
Console.WriteLine("-------------------");
foreach (var file in fileList)
{
Console.WriteLine(file.FullName);
}
Console.WriteLine("-------------------");
Console.WriteLine("End Reading Files");
Console.ReadLine();
}
In above code first I have defined a variable named as folderPath, this variable we will use to store the folder path. after that I have checked path exist or not if path exists on that case code will execute further. After that I have created object for DirectoryInfo. In this I have passed the folder path which is holding the path of the folder. Now declare a variable and use DirectoryInfo object to get all the files present in the folder. After getting all the files I have used a foreach loop to get each and every file present the folder. I have used Console.WriteLine() to print the file available in the folder.
Now let's run the code to check the output.