Prem
Prem

Reputation: 5987

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

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?

Upvotes: 162

Views: 273044

Answers (3)

Migwell
Migwell

Reputation: 20107

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

That last parameter affects exactly what you're referring to. Set it to AllDirectories to include every file including those in subfolders, or 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

Upvotes: 263

Joezer
Joezer

Reputation: 665

You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

Upvotes: 1

TalentTuner
TalentTuner

Reputation: 17556

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Upvotes: 10

Related Questions