Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace BuildDirectoriesTree
- {
- using System;
- using System.IO;
- /// <summary>
- /// Define classes File { string name, int size } and Folder { string name, File[] files, Folder[] childFolders } and using them build a tree keeping all files and folders on the hard drive starting from C:\WINDOWS. Implement a method that calculates the sum of the file sizes in given subtree of the tree and test it accordingly. Use recursive DFS traversal.
- /// </summary>
- public class BuildDirectoriesTree
- {
- public static void Main()
- {
- string rootDirectory = @"C:\Windows";
- string dirName = "Windows";
- Folder main = new Folder(dirName);
- Folder tree = Tree.TraverseDirectory(rootDirectory, ref main);
- long sum = Tree.CalculateFilesSum(tree);
- Console.WriteLine("The total size of the files is: {0} bytes", sum);
- }
- }
- public class File
- {
- public File(string name, long size)
- {
- this.Name = name;
- this.Size = size;
- }
- public File(string name) : this(name, 0)
- {
- }
- public string Name { get; set; }
- public long Size { get; set; }
- }
- public class Folder
- {
- public Folder(string name)
- {
- this.Name = name;
- }
- public string Name { get; set; }
- public File[] Files { get; set; }
- public Folder[] ChildFolders { get; set; }
- }
- public class Tree
- {
- public static Folder TraverseDirectory(string path, ref Folder root)
- {
- DirectoryInfo directory = new DirectoryInfo(path);
- string directoryName = directory.Name;
- root = new Folder(directoryName);
- FileInfo[] currentDirectoryFiles = directory.GetFiles();
- root.Files = new File[currentDirectoryFiles.Length];
- for (int i = 0; i < currentDirectoryFiles.Length; i++)
- {
- string fileName = currentDirectoryFiles[i].Name;
- long length = currentDirectoryFiles[i].Length;
- root.Files[i] = new File(fileName, length);
- }
- DirectoryInfo[] currentDirectorySubDirectories = directory.GetDirectories();
- root.ChildFolders = new Folder[currentDirectorySubDirectories.Length];
- for (int i = 0; i < currentDirectorySubDirectories.Length; i++)
- {
- try
- {
- string dirName = currentDirectorySubDirectories[i].Name;
- path = currentDirectorySubDirectories[i].FullName;
- Folder currentSubFolder = new Folder(dirName);
- TraverseDirectory(path, ref currentSubFolder);
- root.ChildFolders[i] = currentSubFolder;
- }
- catch (System.UnauthorizedAccessException)
- {
- continue;
- }
- }
- return root;
- }
- public static long CalculateFilesSum(Folder folder)
- {
- long currentSum = 0;
- foreach (var file in folder.Files)
- {
- currentSum += file.Size;
- }
- foreach (var childFolder in folder.ChildFolders)
- {
- long childSum = CalculateFilesSum(childFolder);
- currentSum += childSum;
- }
- return currentSum;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement