private void buttonAnalyse_Click(object sender, EventArgs e) { string path = textFilePath.Text; string folderName = (path.LastIndexOf('\\') + 1 < path.Length) ? path.Substring(path.LastIndexOf('\\') + 1) : path.Substring(0, path.LastIndexOf('\\') - 1); Folder rootFolder = new Folder(folderName, path); rootFolder.calculateSizes(); populateData(rootFolder); }
// Recursively add rows to the data table private void addRows(Folder folder, DataTable table) { DataRow newRow = table.NewRow(); newRow["Folder Name"] = folder.Name; newRow["Path"] = folder.Path; newRow["Total Size"] = reformatSize(folder.TotalSize); newRow["File Size"] = reformatSize(folder.FileSize); newRow["Total Size #"] = folder.TotalSize; newRow["File Size #"] = folder.FileSize; table.Rows.Add(newRow); // Recurse for subfolders: foreach (Folder subFolder in folder.Subdirectories) { addRows(subFolder, table); } }
// Add data to the table private void populateData(Folder rootFolder) { DataSet sizes = new DataSet("FolderSizes"); DataTable sizesTable = sizes.Tables.Add("Sizes"); // Add the table's columns sizesTable.Columns.Add("Folder Name", typeof(string)); DataColumn folderPath = sizesTable.Columns.Add("Path", typeof(string)); sizesTable.Columns.Add("Total Size", typeof(string)); sizesTable.Columns.Add("File Size", typeof(string)); sizesTable.Columns.Add("Total Size #", typeof(long)); sizesTable.Columns.Add("File Size #", typeof(long)); sizesTable.PrimaryKey = new DataColumn[] { folderPath }; // Add the rows addRows(rootFolder, sizesTable); // Add table to the DataGridView dataGridView1.DataSource = sizes.Tables["Sizes"]; }
// Calculate the file sizes and total sizes public void calculateSizes() { string[] files = null; string[] subDirectories = null; try { files = Directory.GetFiles(Path); subDirectories = Directory.GetDirectories(Path); } catch (UnauthorizedAccessException e) { // For now, just console log inaccessible files (later create a proper log) System.Diagnostics.Debug.Write(e.Message); } catch (System.IO.DirectoryNotFoundException e) { System.Diagnostics.Debug.Write(e.Message); } if (files != null) { foreach (string file in files) { try { FileSize += new FileInfo(file).Length; } catch (FileNotFoundException e) { System.Diagnostics.Debug.Write(e.Message); } } // Iterate through the sub folders foreach (string subDirectory in subDirectories) { // Do not iterate through reparse points if ((File.GetAttributes(subDirectory) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint) { string folderName = (subDirectory.LastIndexOf('\\') + 1 < subDirectory.Length) ? subDirectory.Substring(subDirectory.LastIndexOf('\\') + 1) : subDirectory.Substring(0, subDirectory.LastIndexOf('\\') - 1); Folder newFolder = new Folder(folderName, subDirectory); newFolder.calculateSizes(); TotalSize += newFolder.TotalSize; // Store the new folder in its parent's subdirectory list Subdirectories.Add(newFolder); } } } TotalSize += FileSize; }