How to loop through all the files in a directory in c # .net?

Prem picture Prem · Nov 23, 2010 · Viewed 190.4k times · Source

I want to get the files in folder and also in its subfolders.The following code does not get the files in its subfolder:

string[] files = Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs");

Can anyone Please tell me how to implement this in c# .net?

Answer

Migwell picture Migwell · Nov 23, 2010
string[] files = 
    Directory.GetFiles(txtPath.Text, "*ProfileHandler.cs", SearchOption.AllDirectories);

That last parameter effects exactly what you're referring to. Set it to AllDirectories for every file including in subfolders, and set it to TopDirectoryOnly if you only want to search in the directory given and not subfolders.

Refer to MDSN for details: https://msdn.microsoft.com/en-us/library/ms143316(v=vs.110).aspx