c# Get all files from Directory and sub directories

Hi Guys,

Today I will show you how you can utilize .NET’s inbuilt API function to get list of all files under a directory and all its subdirectories.

First lets get files from a given Directory

Lets assume that the target directory structure is one show below.

C:\cutils\License.txt
C:\cutils\print.exe
C:\cutils\Readme.txt
C:\cutils\RackSpaceWindowsClient
C:\cutils\RackSpaceWindowsClient\License.txt

If you want to get all files under c:\cutils you can do so using the code below

[geshi lang=”csharp” nums=”1″ target=”_self” ]

What if you want to get files in the subdirectories of c:\utils

Get files from a given Directory and its subdirectories

[geshi lang=”csharp” nums=”1″ target=”_self” ]

 

In above code passing SearchOption.AllDirectories as third param to Directory.GetFiles()  is the key.

Lets talk about second param where I passes “*.*” Second param is a search pattern which will be applied as a filter. Ok lets say if you want to print files that has extension txt you can do so by passing in *.txt as a second param value. Code below shows that

[geshi lang=”csharp” nums=”1″ target=”_self” ]

As you see the above result does not include c:\cutils\print.exe

I hope this post helped you.

Cheers

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.