Skip to content

Commit dbd04b7

Browse files
authored
Add extension methods for validating subdirectory relationships (#1753)
- Implement `IsSubPathOf` for `IFileInfo` and `IDirectoryInfo` to check if a directory or file is a subpath of a given parent directory. This in preparation of refactoring.
1 parent ee2d41b commit dbd04b7

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/Elastic.Documentation/Extensions/IFileInfoExtensions.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,28 @@ public static string ReadToEnd(this IFileInfo fileInfo)
1818
using var reader = new StreamReader(stream);
1919
return reader.ReadToEnd();
2020
}
21+
22+
/// Validates <paramref name="file"/> is in a subdirectory of <paramref name="parentDirectory"/>
23+
public static bool IsSubPathOf(this IFileInfo file, IDirectoryInfo parentDirectory)
24+
{
25+
var parent = file.Directory;
26+
return parent is not null && parent.IsSubPathOf(parentDirectory);
27+
}
28+
}
29+
30+
public static class IDirectoryInfoExtensions
31+
{
32+
/// Validates <paramref name="directory"/> is subdirectory of <paramref name="parentDirectory"/>
33+
public static bool IsSubPathOf(this IDirectoryInfo directory, IDirectoryInfo parentDirectory)
34+
{
35+
var parent = directory;
36+
do
37+
{
38+
if (parent.FullName == parentDirectory.FullName)
39+
return true;
40+
parent = parent.Parent;
41+
} while (parent != null);
42+
43+
return false;
44+
}
2145
}

0 commit comments

Comments
 (0)