Reputation:
This is what I've done so far:
class Program
{
static void Main(string[] args)
{
DirectoryInfo startDirectory = new DirectoryInfo(@"C:\Users\Angelo\Desktop\ExerciseTest");
string output = "";
DirectoryInfo[] subDirectoryes = startDirectory.GetDirectories();
for (int i = 0; i < subDirectoryes.Length; i++)
{
output = output + subDirectoryes[i].ToString() + "\r\n";
}
Console.WriteLine(output);
Console.ReadLine();
}
}
This gives me as a result the first subfolders of the specified folder, the problem is that I need to find all the subfolders,subsubfolders,subsubsubfolders etc.. and files in the specified folder, and then output them with this indentation:
I've been trying to do it many times but I can't figure out how, maybe I'm missing some command (this is the first time I program with c# System.IO) can you please give me some tips or tell me what commands I should use? I'm going crazy.
Upvotes: 0
Views: 321
Reputation: 731
In order to go through all the subfolders, you need recursive function. Basically, you have to repeat the procedure that you apply currently only for root directory to all the directories that you encounter.
Edit: Had to take a little while to provide this code example:
class Program
{
static void Main(string[] args)
{
var basePath = @"C:\Users\Angelo\Desktop\ExerciseTest";
DirectoryInfo startDirectory = new DirectoryInfo(basePath);
IterateDirectory(startDirectory, 0);
Console.ReadLine();
}
private static void IterateDirectory(DirectoryInfo info, int level)
{
var indent = new string('\t', level);
Console.WriteLine(indent + info.Name);
var subDirectories = info.GetDirectories();
foreach(var subDir in subDirectories)
{
IterateDirectory(subDir, level + 1);
}
}
}
A bit of an explanation, what the IterateDirectory does (as requested):
IterateDirectory
method with level
increased by one.This is a rather standard approach for going through tree-like structures.
Upvotes: 0
Reputation: 29720
There is an overload of GetDirectories
you should use that allows you to define the search scope:
DirectoryInfo[] subDirectoryes =
startDirectory.GetDirectories("*", SearchOption.AllDirectories);
This will get all directories, including all the subdirectories all the way down.
The first argument is a search text filter, "*" will find all folders.
A complete example with indentation:
void Main()
{
var path = @"C:\Users\Angelo\Desktop\ExerciseTest";
var initialDepth = path.Split('\\').Count();
DirectoryInfo startDirectory = new DirectoryInfo(path);
StringBuilder sb = new StringBuilder();
DirectoryInfo[] subDirectoryes = startDirectory.GetDirectories("*", SearchOption.AllDirectories);
for (int i = 0; i < subDirectoryes.Length; i++)
{
var level = subDirectoryes[i].FullName.Split('\\').Count() - initialDepth;
sb.AppendLine($"{new string('\t', level)}{subDirectoryes[i].Name}");
}
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
Upvotes: 2