A typical recursive application is to traverse the target folder, print or display all the files and folders in the folder, and recursively calculate the total size of the target folder.
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: console. writeline ("Enter the target folder ");
6: string path = Console.ReadLine();
7: FindFoldersAndFiles(path);
8: Console.WriteLine("\r\n");
9: console. writeline ("total target folder size: {0} bytes", getdirectorylength (PATH ));
10: Console.ReadKey();
11: }
12:
13: // recursive all files and folders in the target folder
14: private static void FindFoldersAndFiles(string path)
15: {
16: console. writeline ("folder" + path );
17: // traverse all objects in the target folder
18: foreach (string fileName in Directory.GetFiles(path))
19: {
20: Console.WriteLine("┣" + fileName);
21: }
22:
23: // traverse all the folders in the target folder
24: foreach (string directory in Directory.GetDirectories(path))
25: {
26: FindFoldersAndFiles(directory);
27: }
28: }
29:
30: // recursively calculate the folder size
31: static long GetDirectoryLength(string path)
32: {
33: if (!Directory.Exists(path))
34: {
35: return 0;
36: }
37:
38: long size = 0;
39:
40: // traverse all objects in the specified path
41: DirectoryInfo di = new DirectoryInfo(path);
42: foreach (FileInfo fi in di.GetFiles())
43: {
44: size += fi.Length;
45: }
46:
47: // traverse all folders in the specified path
48: DirectoryInfo[] dis = di.GetDirectories();
49: if (dis.Length > 0)
50: {
51: for (int i = 0; i < dis.Length; i++)
52: {
53: size += GetDirectoryLength(dis[i].FullName);
54: }
55: }
56:
57: return size;
58: }
59: }
60:
61:
When traversing the target folder, recursively display all the folders and files in the target folder, and recursively calculate the total size of the target folder.