0

How do I list the contents of a given directory?

We can say private string directory = @"C:\"; and what I then want is to use Console.WriteLine() to display the contents of directory.

However, after hours of research on this site, I still could not find an answer that worked. I have tried solutions like Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories)) but the code failed to build. How do I fix this?

I have this at the beginning of my code:

using System;
using System.Collections.Generic;
using System.Text;

Am I missing something? What am I doing wrong? How do I fix this?

  • Possible duplicate of [Getting all file names from a folder using C#](http://stackoverflow.com/questions/14877237/getting-all-file-names-from-a-folder-using-c-sharp) – Alex K. Oct 20 '15 at 23:51
  • @AlexK. I think this is more of a case of finding the correct using statement rather than enumerating file names – MikeH Oct 20 '15 at 23:54
  • Show us the whole code that failed to build. We can then help you fix it. – Enigmativity Oct 21 '15 at 00:20

2 Answers2

1

Directory.EnumerateDirectories() returns an enumeration of all subdirectories of the specified directory.

foreach (var dir in Directory.EnumerateDirectories(@"C:\"))
{
    Console.WriteLine(dir);
}

If however or in addition you wish to specify all files, use File.GetFiles()

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

Both of these are in the System.IO namespace, so include this in your using section

using System.IO;
Eric J.
  • 147,927
  • 63
  • 340
  • 553
0
using System.IO;

Visual Studio offers a nice feature for the situations where you don't know which using statement you need: Right click on Directory and the second option (in VS 2013) is "Resolve", then a sub-menu with "using System.IO". Click that sub-menu item and it will automatically add the using statement.

MikeH
  • 4,242
  • 1
  • 17
  • 32