Last active
October 8, 2018 06:50
-
-
Save ssippe/2d4bff4808f44f32d32bf10ad172f7f0 to your computer and use it in GitHub Desktop.
FindRelativePathInAncestors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Search for relativePath with respect to (w.r.t.) the current directory and if it doesn't exist, | |
/// search w.r.t. the current parent directory, then the grandparent and so on until the path is found | |
/// or the root it hit. Works for files or directories. | |
/// </summary> | |
/// <returns></returns> | |
public static string FindRelativePathInAncestors(string relativePath, string startDirectory) | |
{ | |
relativePath = relativePath.TrimStart(Path.DirectorySeparatorChar); | |
int level = 0; | |
var root = Path.GetPathRoot(startDirectory); | |
while (true) | |
{ | |
var prefix = "." + string.Join("/", Enumerable.Repeat("..", level)); | |
var absolutePrefix = Path.GetFullPath(Path.Combine(startDirectory, prefix)); | |
var testPath = Path.Combine(absolutePrefix, relativePath); | |
if (File.Exists(testPath) || Directory.Exists(testPath)) | |
return testPath; | |
if (absolutePrefix == root) | |
return null; | |
level++; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment