From 47421b2d1cfc520b61e564821e7f672c36ebe785 Mon Sep 17 00:00:00 2001 From: Ionite Date: Sun, 22 Oct 2023 18:44:58 -0400 Subject: [PATCH] Add DirectoryPath Enumeration methods --- .../Models/FileInterfaces/DirectoryPath.cs | 47 ++++++++++++++++++- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/StabilityMatrix.Core/Models/FileInterfaces/DirectoryPath.cs b/StabilityMatrix.Core/Models/FileInterfaces/DirectoryPath.cs index 8cab7af5..a996faf6 100644 --- a/StabilityMatrix.Core/Models/FileInterfaces/DirectoryPath.cs +++ b/StabilityMatrix.Core/Models/FileInterfaces/DirectoryPath.cs @@ -1,4 +1,5 @@ -using System.Diagnostics.CodeAnalysis; +using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; using StabilityMatrix.Core.Converters.Json; @@ -6,7 +7,7 @@ namespace StabilityMatrix.Core.Models.FileInterfaces; [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] [JsonConverter(typeof(StringJsonConverter))] -public class DirectoryPath : FileSystemPath, IPathObject +public class DirectoryPath : FileSystemPath, IPathObject, IEnumerable { private DirectoryInfo? info; @@ -133,8 +134,50 @@ public class DirectoryPath : FileSystemPath, IPathObject public FilePath JoinFile(params FilePath[] paths) => new(Path.Combine(FullPath, Path.Combine(paths.Select(path => path.FullPath).ToArray()))); + /// + /// Returns an enumerable collection of files that matches + /// a specified search pattern and search subdirectory option. + /// + public IEnumerable EnumerateFiles( + string searchPattern = "*", + SearchOption searchOption = SearchOption.TopDirectoryOnly + ) => Info.EnumerateFiles(searchPattern, searchOption).Select(file => new FilePath(file)); + + /// + /// Returns an enumerable collection of directories that matches + /// a specified search pattern and search subdirectory option. + /// + public IEnumerable EnumerateDirectories( + string searchPattern = "*", + SearchOption searchOption = SearchOption.TopDirectoryOnly + ) => + Info.EnumerateDirectories(searchPattern, searchOption) + .Select(directory => new DirectoryPath(directory)); + public override string ToString() => FullPath; + /// + public IEnumerator GetEnumerator() + { + return Info.EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly) + .Select( + fsInfo => + fsInfo switch + { + FileInfo file => new FilePath(file), + DirectoryInfo directory => new DirectoryPath(directory), + _ => throw new InvalidOperationException("Unknown file system info type") + } + ) + .GetEnumerator(); + } + + /// + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + // DirectoryPath + DirectoryPath = DirectoryPath public static DirectoryPath operator +(DirectoryPath path, DirectoryPath other) => new(Path.Combine(path, other.FullPath));