Reputation:
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?
Upvotes: 0
Views: 454
Reputation: 150178
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;
Upvotes: 1
Reputation: 4395
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.
Upvotes: 0