Advertisement
Dragon53535

Recursive File Size C#

May 24th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.82 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7.  
  8. class DirectorySize {
  9.  
  10.  
  11.     //Member variables
  12.  
  13.     //Is our directory we're technically searching in valid, and moreso can we actually do anything.
  14.     private bool Valid = true;
  15.  
  16.     //The original directory we're looking in.
  17.     private string baseDir;
  18.  
  19.     //Our dictionary of each directory in the baseDir with the size as a long
  20.     private Dictionary<string, long> directorys;
  21.  
  22.     //Constructors
  23.  
  24.     //direct is what directory we're going to have as our baseDir
  25.     //subDir is a bool stating if we want to individualize each subdirectory in baseDir so each gets it's own size. True for the example
  26.     public DirectorySize(string direct, bool subDir) {
  27.  
  28.         //If our directory actually exists, just gotta make sure
  29.         if (Directory.Exists(direct)) {
  30.  
  31.             //Set baseDir to direct, and initialize directorys. Could of actually done that above, but meh.
  32.             baseDir = direct;
  33.             directorys = new Dictionary<string, long>();
  34.  
  35.             //If we want the subdirectory sizes
  36.             if (subDir) {
  37.  
  38.                 //Just add them into the dictionary with a "size" of 0
  39.                 foreach (string directs in Directory.GetDirectories(direct)) {
  40.                     directorys[directs] = 0;
  41.                 }
  42.             } else {
  43.                 //Just add our base directory into the dictionary with size of 0
  44.                 directorys[direct] = 0;
  45.             }
  46.         } else {
  47.             //We're not a valid setup, we would need to be remade with a different starting directory
  48.             Valid = false;
  49.         }
  50.     }
  51.  
  52.     //Default values for direct and subDir are C:\ and true
  53.     public DirectorySize(string direct) : this(direct, true) {
  54.  
  55.     }
  56.     public DirectorySize() : this(@"C:\") {
  57.     }
  58.  
  59.  
  60.     //String reverse function, I need it for adding the comma's
  61.     private string Reverse(string s) {
  62.  
  63.         //Turn s to an array, reverse the array, then return the reversed array as a string
  64.         char[] c = s.ToCharArray();
  65.         Array.Reverse(c);
  66.         return new string(c);
  67.     }
  68.  
  69.     //Recursive function for getting the size of a given directory and any directory's in them as a long
  70.     //Directory is the current directory, stringList is our messages list so what directory's we can't access.
  71.     private long recurFindSize(DirectoryInfo directory, List<string> stringList) {
  72.  
  73.         //Trycatch block for if we can't access the directory.
  74.         try {
  75.  
  76.             //Our long value to return, starts at 0 so I can add to it
  77.             //Originally I had it as an int when I started this, turns out that file.Length is a long and c# don't like long to int conversion
  78.             long returnInt = 0;
  79.  
  80.             //Loop through each fileInfo file inside the directory's files
  81.             foreach (var file in directory.EnumerateFiles()) {
  82.  
  83.                 //Add the length
  84.                 returnInt += file.Length;
  85.             }
  86.  
  87.             //Loop through each DirectoryInfo direct in directory
  88.             foreach (var direct in directory.EnumerateDirectories()) {
  89.  
  90.                 //Add return value from calling recurrsive function to the long we need to return
  91.                 returnInt += recurFindSize(direct, stringList);
  92.             }
  93.  
  94.             //Return our long
  95.             return returnInt;
  96.  
  97.         } catch (Exception) {
  98.  
  99.             //If we had an exception, add our directory path to the error list, and return 0
  100.             stringList.Add(directory.FullName);
  101.             return 0;
  102.         }
  103.     }
  104.  
  105.     //Our public function for finding the size of a directory, makes it easy to use really based off directory's name
  106.     public long findSize(string fileName, List<string> stringList) {
  107.         return recurFindSize(new DirectoryInfo(fileName), stringList);
  108.     }
  109.  
  110.     //Our printing function
  111.     public void printSizes() {
  112.  
  113.         //If we're a valid class
  114.         if (Valid) {
  115.  
  116.             //Our error list, and a copy of the directorys dictionary
  117.             //Need the copy because we cannot edit the original while enumerating through it
  118.             List<string> errorList = new List<string>();
  119.             Dictionary<string, long> s = new Dictionary<string, long>(directorys);
  120.  
  121.  
  122.             //Enumerate through the copied dictionary
  123.             foreach (var entry in s) {
  124.  
  125.                 //Set the sizes in our original dictionary and pass it the directory name, and our errorList
  126.                 directorys[entry.Key] = findSize(entry.Key, errorList);
  127.             }
  128.  
  129.             //If we had any directorys we couldn't access, print the banner and each directory
  130.             if (errorList.Count > 0) {
  131.                 Console.WriteLine("=========================================");
  132.                 Console.WriteLine("Messages");
  133.                 Console.WriteLine("=========================================");
  134.                 Console.WriteLine("");
  135.  
  136.                 foreach (string fileNames in errorList) {
  137.                     Console.WriteLine("Could not read directory: [{0}]", fileNames);
  138.                 }
  139.                 Console.WriteLine("");
  140.             }
  141.  
  142.             //Use linq to order our KeyValuePairs in the dictionary based on the size
  143.             var ordered = from p in directorys orderby p.Value descending select p;
  144.  
  145.             //Print the banner
  146.             Console.WriteLine("=========================================");
  147.             Console.WriteLine("Directory Sizes");
  148.             Console.WriteLine("=========================================");
  149.             Console.WriteLine("");
  150.  
  151.             //Print the base directory
  152.             Console.WriteLine("Base Directory: [{0}]\n", baseDir);
  153.  
  154.             //Our padding size, starts at 0, and will be the size of the first/largest (they're the same) value in our KeyValuePair Array
  155.             var padSize = 0;
  156.  
  157.             //Loop through our ordered array
  158.             foreach (var current in ordered) {
  159.  
  160.                 //Adding commas
  161.  
  162.                 //Reverse string, and setup empty string to start adding into
  163.                 string str = Reverse(current.Value.ToString());
  164.                 string endStr = "";
  165.  
  166.                 //Initialize i to 0. i is our variable keeping track of which character we're on.
  167.                 int i = 0;
  168.  
  169.                 //foreach character in our reversed string, I could of gone just with a for loop, but I'm lazy
  170.                 foreach (char c in str) {
  171.  
  172.                     //If the character we're at is the one after we want to put a comma, first thousands place, first millions, etc
  173.                     if (i % 3 == 0 && i != 0) {
  174.  
  175.                         //Add a comma to our string we are building
  176.                         endStr += ",";
  177.                     }
  178.  
  179.                     //Add the current character to our string, and increment i
  180.                     endStr += c;
  181.                     i++;
  182.                 }
  183.  
  184.                 //Reverse our size string.
  185.                 endStr = Reverse(endStr);
  186.  
  187.                 //If we haven't set out padding size, set it now to the size of our build string.
  188.                 if (padSize == 0) {
  189.                     padSize = endStr.Length;
  190.                 }
  191.  
  192.                 //Print out the directory size. with PadLeft on the string, and then after two spaces print the directory.
  193.                 Console.WriteLine("{0}  {1}", endStr.PadLeft(padSize), current.Key);
  194.             }
  195.  
  196.         }
  197.     }
  198. }
  199.  
  200. class WeekThirteenProblemOne {
  201.     //Just test main.
  202.     public static void Main() {
  203.         Console.Write("Please enter a directory: ");
  204.         string directory = Console.ReadLine();
  205.         Console.WriteLine("\n\n");
  206.         DirectorySize dir = new DirectorySize(directory);
  207.         dir.printSizes();
  208.     }
  209. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement