How to Read /Get Files from a Folder in .Net Core Using C#

How to read or get or retrieve files present in a local folder using c#.net. Here I have used .Net core console application in c#.
In today's article I will show you how you can read, get or extract all the files available in a folder using c#.net. This code you can use in your windows application, console application.  This will help you to get file from local folder. For here we will demonstrate by using a .NET core console application in c#.net.

To demonstrate the example first we will create a folder and add some files. For example, please check the below image.

How to Read /Get Files from a Folder in .Net Core Using C#

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.

How to Read /Get Files from a Folder in .Net Core Using C#
How to Read Get Files from a Folder in .Net Core Using C#.zip 226KiB

Post a Comment