using System; using System.Collections.Generic; using System.IO; using System.Linq; using SabreTools.Library.Data; using NaturalSort; namespace SabreTools.Library.IO { /// /// Extensions to Directory functionality /// public static class DirectoryExtensions { /// /// Cleans out the temporary directory /// /// Name of the directory to clean out public static void Clean(string dir) { foreach (string file in Directory.EnumerateFiles(dir, "*", SearchOption.TopDirectoryOnly)) { FileExtensions.TryDelete(file); } foreach (string subdir in Directory.EnumerateDirectories(dir, "*", SearchOption.TopDirectoryOnly)) { TryDelete(subdir); } } /// /// Ensure the output directory is a proper format and can be created /// /// Directory to check /// True if the directory should be created, false otherwise (default) /// True if this is a temp directory, false otherwise /// Full path to the directory public static string Ensure(string dir, bool create = false, bool temp = false) { // If the output directory is invalid if (string.IsNullOrWhiteSpace(dir)) { if (temp) dir = Path.GetTempPath(); else dir = Environment.CurrentDirectory; } // Get the full path for the output directory dir = Path.GetFullPath(dir); // If we're creating the output folder, do so if (create) Directory.CreateDirectory(dir); return dir; } /// /// Retrieve a list of just directories from inputs /// /// List of strings representing directories and files /// True if the parent name should be included in the ParentablePath, false otherwise (default) /// List of strings representing just directories from the inputs public static List GetDirectoriesOnly(List inputs, bool appendparent = false) { List outputs = new List(); for (int i = 0; i < inputs.Count; i++) { string input = inputs[i]; // If we have a null or empty path if (string.IsNullOrEmpty(input)) continue; // If we have a wildcard string pattern = "*"; if (input.Contains("*") || input.Contains("?")) { pattern = Path.GetFileName(input); input = input.Substring(0, input.Length - pattern.Length); } // Get the parent path in case of appending string parentPath; try { parentPath = Path.GetFullPath(input); } catch (Exception ex) { Globals.Logger.Error(ex, $"An exception occurred getting the full path for '{input}'"); continue; } if (Directory.Exists(input)) { List directories = GetDirectoriesOrdered(input, pattern); foreach (string dir in directories) { try { outputs.Add(new ParentablePath(Path.GetFullPath(dir), appendparent ? parentPath : string.Empty)); } catch (PathTooLongException ex) { Globals.Logger.Warning(ex, $"The path for '{dir}' was too long"); } catch (Exception ex) { Globals.Logger.Error(ex, $"An exception occurred processing '{dir}'"); } } } } return outputs; } /// /// Retrieve a list of directories from a directory recursively in proper order /// /// Directory to parse /// Optional pattern to search for directory names /// List with all new files private static List GetDirectoriesOrdered(string dir, string pattern = "*") { return GetDirectoriesOrderedHelper(dir, new List(), pattern); } /// /// Retrieve a list of directories from a directory recursively in proper order /// /// Directory to parse /// List representing existing files /// Optional pattern to search for directory names /// List with all new files private static List GetDirectoriesOrderedHelper(string dir, List infiles, string pattern) { // Take care of the files in the top directory List toadd = Directory.EnumerateDirectories(dir, pattern, SearchOption.TopDirectoryOnly).ToList(); toadd.Sort(new NaturalComparer()); infiles.AddRange(toadd); // Then recurse through and add from the directories foreach (string subDir in toadd) { infiles = GetDirectoriesOrderedHelper(subDir, infiles, pattern); } // Return the new list return infiles; } /// /// Retrieve a list of just files from inputs /// /// List of strings representing directories and files /// True if the parent name should be be included in the ParentablePath, false otherwise (default) /// List of strings representing just files from the inputs public static List GetFilesOnly(List inputs, bool appendparent = false) { List outputs = new List(); for (int i = 0; i < inputs.Count; i++) { string input = inputs[i].Trim('"'); // If we have a null or empty path if (string.IsNullOrEmpty(input)) continue; // If we have a wildcard string pattern = "*"; if (input.Contains("*") || input.Contains("?")) { pattern = Path.GetFileName(input); input = input.Substring(0, input.Length - pattern.Length); } // Get the parent path in case of appending string parentPath; try { parentPath = Path.GetFullPath(input); } catch (Exception ex) { Globals.Logger.Error(ex, $"An exception occurred getting the full path for '{input}'"); continue; } if (Directory.Exists(input)) { List files = GetFilesOrdered(input, pattern); foreach (string file in files) { try { outputs.Add(new ParentablePath(Path.GetFullPath(file), appendparent ? parentPath : string.Empty)); } catch (PathTooLongException ex) { Globals.Logger.Warning(ex, $"The path for '{file}' was too long"); } catch (Exception ex) { Globals.Logger.Error(ex, $"An exception occurred processing '{file}'"); } } } else if (File.Exists(input)) { try { outputs.Add(new ParentablePath(Path.GetFullPath(input), appendparent ? parentPath : string.Empty)); } catch (PathTooLongException ex) { Globals.Logger.Warning(ex, $"The path for '{input}' was too long"); } catch (Exception ex) { Globals.Logger.Error(ex, $"An exception occurred processing '{input}'"); } } } return outputs; } /// /// Retrieve a list of files from a directory recursively in proper order /// /// Directory to parse /// Optional pattern to search for directory names /// List with all new files public static List GetFilesOrdered(string dir, string pattern = "*") { return GetFilesOrderedHelper(dir, new List(), pattern); } /// /// Retrieve a list of files from a directory recursively in proper order /// /// Directory to parse /// List representing existing files /// Optional pattern to search for directory names /// List with all new files private static List GetFilesOrderedHelper(string dir, List infiles, string pattern) { // Take care of the files in the top directory List toadd = Directory.EnumerateFiles(dir, pattern, SearchOption.TopDirectoryOnly).ToList(); toadd.Sort(new NaturalComparer()); infiles.AddRange(toadd); // Then recurse through and add from the directories List subDirs = Directory.EnumerateDirectories(dir, pattern, SearchOption.TopDirectoryOnly).ToList(); subDirs.Sort(new NaturalComparer()); foreach (string subdir in subDirs) { infiles = GetFilesOrderedHelper(subdir, infiles, pattern); } // Return the new list return infiles; } /// /// Get all empty folders within a root folder /// /// Root directory to parse /// IEumerable containing all directories that are empty, an empty enumerable if the root is empty, null otherwise public static List ListEmpty(string root) { // Check if the root exists first if (!Directory.Exists(root)) return null; // If it does and it is empty, return a blank enumerable if (Directory.EnumerateFileSystemEntries(root, "*", SearchOption.AllDirectories).Count() == 0) return new List(); // Otherwise, get the complete list return Directory.EnumerateDirectories(root, "*", SearchOption.AllDirectories) .Where(dir => Directory.EnumerateFileSystemEntries(dir, "*", SearchOption.AllDirectories).Count() == 0) .ToList(); } /// /// Try to safely delete a directory, optionally throwing the error /// /// Name of the directory to delete /// True if the error that is thrown should be thrown back to the caller, false otherwise /// True if the file didn't exist or could be deleted, false otherwise public static bool TryCreateDirectory(string file, bool throwOnError = false) { // Now wrap creating the directory try { Directory.CreateDirectory(file); return true; } catch (Exception ex) { if (throwOnError) throw ex; else return false; } } /// /// Try to safely delete a directory, optionally throwing the error /// /// Name of the directory to delete /// True if the error that is thrown should be thrown back to the caller, false otherwise /// True if the file didn't exist or could be deleted, false otherwise public static bool TryDelete(string file, bool throwOnError = false) { // Check if the directory exists first if (!Directory.Exists(file)) return true; // Now wrap deleting the directory try { Directory.Delete(file, true); return true; } catch (Exception ex) { if (throwOnError) throw ex; else return false; } } } }