162

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?

2
  • 3
    I've always preferred the MSDN method of doing things. At the bottom of this link they provide a recursive example w/ a console program (C#).
    – Justin
    Commented May 4, 2013 at 1:30
  • 2
    @Panuvin - Note: The MSDN code is a little dangerous. For very large folder and subfolder content (many many files) you can get a StackOverflow exception (because of the recursive code)
    – Joezer
    Commented May 28, 2014 at 7:12

3 Answers 3

262
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

3
  • 6
    This will infinite loop if there's a loop in your folder structure. See msdn.microsoft.com/en-us/library/ms143448.aspx Commented Oct 2, 2013 at 7:31
  • 1
    What is the purpose of the middle parameter?
    – usefulBee
    Commented Oct 13, 2016 at 16:10
  • 4
    It's called searchPattern and it's a filter by which files are selected. In this case it will select all files ending in "ProfileHandler.cs". Have a look at MDSN
    – Migwell
    Commented Oct 13, 2016 at 23:10
10

try below code

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.