EN
C# / .NET - list all dirs and files below given directory
6
points
In C# / .NET it is possible to list directories and files from directory in following ways.
1. Get files and directories from directory example
using System;
using System.IO;
public static class Program
{
public static void Main(string[] args)
{
string path = @"C:\Directories";
string[] files = Directory.GetFiles(path);
string[] directories = Directory.GetDirectories(path);
foreach (string entry in directories)
Console.WriteLine(string.Format("{0,-40} [DIR]", entry));
foreach (string entry in files)
Console.WriteLine(string.Format("{0,-40} [FILE]", entry));
}
}
Output:
C:\Directories\Documents [DIR]
C:\Directories\Downloads [DIR]
C:\Directories\Musics [DIR]
C:\Directories\Pictures [DIR]
C:\Directories\Videos [DIR]
C:\Directories\json.txt [FILE]
C:\Directories\screenshot.png [FILE]
C:\Directories\sound.mp3 [FILE]
C:\Directories\wallpaper.jpg [FILE]
2. Get and filter files from directory example
using System;
using System.IO;
public static class Program
{
public static void Main(string[] args)
{
string path = @"C:\Directories";
string[] files = Directory.GetFiles(path, "*.png");
foreach (string entry in files)
Console.WriteLine(entry);
}
}
Output:
C:\Directories\screenshot.png
3. Get recursively files and directories from directory example
using System;
using System.IO;
public static class Program
{
public static void Main(string[] args)
{
string path = @"C:\Directories";
string[] files = Directory.GetFiles(path, "", SearchOption.AllDirectories);
string[] directories = Directory.GetDirectories(path, "", SearchOption.AllDirectories);
foreach (string entry in directories)
Console.WriteLine(string.Format("{0,-40} [DIR]", entry));
foreach (string entry in files)
Console.WriteLine(string.Format("{0,-40} [FILE]", entry));
}
}
Output:
C:\Directories\Documents [DIR]
C:\Directories\Downloads [DIR]
C:\Directories\Musics [DIR]
C:\Directories\Pictures [DIR]
C:\Directories\Videos [DIR]
C:\Directories\Pictures\Empty [DIR]
C:\Directories\Videos\Home [DIR]
C:\Directories\Videos\Job [DIR]
C:\Directories\json.txt [FILE]
C:\Directories\screenshot.png [FILE]
C:\Directories\sound.mp3 [FILE]
C:\Directories\wallpaper.jpg [FILE]
C:\Directories\Documents\cv.docx [FILE]
C:\Directories\Documents\expences.xlsx [FILE]
C:\Directories\Downloads\jquery.js [FILE]
C:\Directories\Musics\song a.mp3 [FILE]
C:\Directories\Musics\song b.ogg [FILE]
C:\Directories\Musics\song c.wav [FILE]
C:\Directories\Pictures\picture 1.jpg [FILE]
C:\Directories\Pictures\picture 2.jpg [FILE]
C:\Directories\Pictures\picture 3.jpg [FILE]
C:\Directories\Videos\video 1.mp4 [FILE]
C:\Directories\Videos\video 2.mp4 [FILE]
C:\Directories\Videos\Home\video 1.mp4 [FILE]
C:\Directories\Videos\Home\video 2.mp4 [FILE]
C:\Directories\Videos\Job\video 1.mp4 [FILE]
C:\Directories\Videos\Job\video 2.mp4 [FILE]
C:\Directories\Videos\Job\video 3.mp4 [FILE]