tike
tike

Reputation: 548

how to display files inside directory

i am trying to get list of files inside the directory in this case "c:\dir\" (ofcourse i have files inside) and i wanted to display the name of those files in console program build in c#....

initially i did this....

static class Program
    {
        static void Main()
        {
            string[] filePaths = Directory.GetFiles(@"c:\dir\");
            Console.WriteLine();
            Console.Read();


        }
    }

how can i see the name of those files....... any help would be appreciated.....

thank you.

(further i would like to know if possible any idea on sending those file path towards dynamic html page.... any general concept how to do that...)

Upvotes: 4

Views: 10444

Answers (5)

Dan Tao
Dan Tao

Reputation: 128407

If by "file names" you mean literally just the names and not the full paths:

string[] filePaths = Directory.GetFiles(@"c:\dir");
for (int i = 0; i < filePaths.Length; ++i) {
    string path = filePaths[i];
    Console.WriteLine(System.IO.Path.GetFileName(path));
}

Upvotes: 6

Aaron
Aaron

Reputation: 7108

Loop through the files and print them one at a time:

foreach(string folder in Directory.GetDirectories(@"C:\dir"))
{
    Console.WriteLine(folder);
}

foreach(string file in Directory.GetFiles(@"C:\dir"))
{
    Console.WriteLine(file);
}

Upvotes: 4

Giorgi
Giorgi

Reputation: 30883

Keep in mind that if there are many files in the folder you will have memory problems.
.Net 4.0 contains a fix: C# directory.getfiles memory help

Upvotes: 2

Aistina
Aistina

Reputation: 12679

foreach (string filename in filePaths) {
  Console.WriteLine(filename);
}

Upvotes: 3

Larry Hipp
Larry Hipp

Reputation: 6255

foreach(FileInfo f in Directory.GetFiles()) Console.Writeline(f.Name)

Upvotes: 1

Related Questions