Click here to Skip to main content
15,918,303 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello ! I have a noobish question. I want to get all the files from a specific dieectory. The only way i know doing this.. is by this following line of code:

C#
string[] GetFiles = Directory.GetFiles(DirectoryPath);


The problem with GetFiles method is... that i am getting the subdirectories too. Is there a way of getting only the files(for example txt, bmp, ico, launch, cp and e.t.c) ? Thanks !

What I have tried:

I have tried method GetFiles:

string[] GetFiles = Directory.GetFiles(DirectoryPath);

The problem is that it gets the folder too.
Posted
Updated 9-Sep-16 4:34am

Directory.GetFiles()[^] accepts SearchOption[^]. Use TopDirectoryOnly only as a third parameter to that method.

Example:
C#
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string[] files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);

var result = files.Select(a=>Path.GetFileName(a));


Returns:
file1.xlsx
file2.bmp
file3.docx
 
Share this answer
 
v3
Comments
xXxRevolutionxXx 9-Sep-16 11:05am    
I want to get all files from all directories.... the SearchOption.AllDirectories is the only way to achieve this.. so SearchOption.TopDirectoryOnly is not an option for me :(
Maciej Los 9-Sep-16 11:08am    
Really??? Who's wrote that?
I want to get all the files from a specific dieectory.
...
The problem is that it gets the folder too.

There's no problem to change SearchOption parameter.
You should try below
C#
var fileList= Directory
                .GetFiles("Your directory path", "*", SearchOption.AllDirectories)
                .Select(Path.GetFileName);


I am sure, you know how to get the individual file names from the fileList object.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900