rkrishnan
rkrishnan

Reputation:

how do i read the filenames inside the directory to an array

(i am using C# windows application) i want to read all the FileNames of a directory to an array.. how do i read that..

( suppose consider a directory with a names ROOT,ROOT2

Let ROOT1 has a.txt,b.txt,c.txt

let ROOT2 has x.txt,y.txt,z.txt

i just want to read those things to my array ...

what is the way to read that...? ( or ) can you send me the code for that...?

Upvotes: 1

Views: 7569

Answers (4)

stevehipwell
stevehipwell

Reputation: 57508

If there are sub folders you want

string[] oFiles = Directory.GetFiles(sPath, "*", SearchOption.AllDirectories);

otherwise you want

string[] oFiles = Directory.GetFiles(sPath);

or if you want to filter you want

string[] oFiles = Directory.GetFiles(sPath, "*");

To filter by .txt extension replace * with *.txt as the second argument.

Upvotes: 5

Thomas Levesque
Thomas Levesque

Reputation: 292495

string[] fileNames = Directory.GetFiles(directoryPath, "*", SearchOptions.AllDirectories)

Upvotes: 2

Ralph M. Rickenbach
Ralph M. Rickenbach

Reputation: 13193

This is some code to read the files in a directory:

DirectoryInfo di = new DirectoryInfo("c:/root1");
FileInfo[] rgFiles = di.GetFiles("*.*");
foreach(FileInfo fi in rgFiles)
{
   Response.Write("<br><a href=" + fi.Name + ">" + fi.Name + "</a>");       
}

FileInfo is a string array containing all files.

Upvotes: 2

ZombieSheep
ZombieSheep

Reputation: 29953

A call to Directory.GetFiles(directoryPath) is what you want. If you want to go deeper into the structure of the path (get files in subfolders, etc) then qualify the call with SearchOptions.AllDirectories, or try looking here

Upvotes: 1

Related Questions