Recursively display all files and folders in the target folder, calculate the size of the target folder, and recursively
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.
JAVA traverses all files in a folder --- (recursion)
Import java. io. File;
Public class Test {
Public static void main (String [] args) throws Exception {
// Recursively display all folders and files in drive C
File root = new File ("c :");
ShowAllFiles (root );
}
Final static void showAllFiles (File dir) throws Exception {
File [] fs = dir. listFiles ();
For (int I = 0; I <fs. length; I ++ ){
System. out. println (fs [I]. getAbsolutePath ());
If (fs [I]. isDirectory ()){
Try {
ShowAllFiles (fs [I]);
} Catch (Exception e ){}
}
}
}
}
How to directly display the folder size in win7, the size of all folders is clear at a glance, no need to right-click the attribute
Try Quick View Folder Size.