In this Article we will discuss how to get or fetch the files from the Directory or Folder using C#.
There are multiple functions we can use to fetch the files from the Directory. One of it is, and the simple one is, GetFiles method from the Directory class.
The Syntax of GetFiles method looks like below:
String[] GetFiles(String directory_path);
GetFiles method will fetch the files from the directory which is provided through the argument “directory_path”.
Compile the program at the command prompt and run it.
csc getfiles.cs
getfiles.exe
Observer that, this program will display all the files which are listed in the directory “C:\”.
Lets’ look at another variation of GetFiles method; which will fetch the files based on some search pattern. For example: if you want to fetch only the text files, instead of all the files; this variation of GetFiles is really helpful.
The Syntax of this variation of GetFiles method looks like below:
String[] GetFiles(String directory_path, String search_pattern);
“directory_path” is the directory path & “search_pattern” is the pattern you would like to give. For example: to fetch only the text files, you can give “*.txt” as the pattern.
Another variance of GetFiles is:
String[] GetFiles(String directory_path, String search_pattern, SearchOption search_option);
This is helpful to fetch the files from the Directory & its’ sub Directories too. The last argument, SearchOption is an enumeration. It has two members:
TopDirectoryOnly – which helps to fetch the files only from the directory mentioned in “directory_path” argument.
AllDirectories – which helps to fetch the files from the directory & its’ sub-directories too.
Lets’ see the complete example:
You will see below Output once you run the Program.
C:\>getfiles-new.exe
— Display files listed in the directory —
C:\WorkingFolder\apache-tomcat-8.0.9.zip
C:\WorkingFolder\Notes.txt
C:\WorkingFolder\out.txt
C:\WorkingFolder\rubyinstaller-2.0.0-p481-x64.exe
— Display only the text files listed in the directory —
C:\WorkingFolder\Notes.txt
C:\WorkingFolder\out.txt
— Display the files listed in the directory & its’ sub-directories —
C:\WorkingFolder\apache-tomcat-8.0.9.zip
C:\WorkingFolder\Notes.txt
C:\WorkingFolder\out.txt
C:\WorkingFolder\rubyinstaller-2.0.0-p481-x64.exe
C:\WorkingFolder\Images\bus-timings.PNG
C:\WorkingFolder\Images\unlimited-web-hosting.png
Observe the results. First block displays all the files which are listed in the directory “C:\WorkingFolder”. Second block, displays only the text files. Third block displays all the files which are in “C:\WorkingFolder” and its’ sub-directory “C:\WorkingFolder\Images”.
There are other functions too to fetch the files from the directories. But GetFiles is the simple one to use.
Don’t forget to post your feedback through the comments.
(Raju)