Last active
November 16, 2016 12:36
-
-
Save kakkun61/1874227fc6ce87dcc7bb9c56b2d74021 to your computer and use it in GitHub Desktop.
normalizing path
This file contains hidden or 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
private static string Normalize(string path) | |
{ | |
// Example: path = "///1/..//../2/3/" | |
var trimed = path.Trim(new char[]{ Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); // "1/..//../2//3" | |
Console.WriteLine("trimed: " + trimed); | |
var maxDep = 1 + trimed.Count(c => c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar); // 6 | |
Console.WriteLine("maxDep: " + maxDep); | |
var tmpParentPath = ""; // will be "a/a/a/a/a/a/" | |
for (var i = 0; i < maxDep; i++) | |
tmpParentPath = Path.Combine(tmpParentPath, "a"); | |
tmpParentPath = tmpParentPath + Path.DirectorySeparatorChar; | |
Console.WriteLine("tmpParentPath: " + tmpParentPath); | |
var tmpParentFullPath = Path.GetFullPath(tmpParentPath); // "/working/directory/a/a/a/a/a/a/" | |
Console.WriteLine("tmpParentFullPath: " + tmpParentFullPath); | |
var fullPath = Path.GetFullPath(Path.Combine(tmpParentPath, trimed)); // "/working/directory/a/a/a/a/a/2/3" | |
Console.WriteLine("fullPath: " + fullPath); | |
var tmpParentFullPathUri = new Uri(tmpParentFullPath); // "file:///working/directory/a/a/a/a/a/a/" | |
Console.WriteLine("tmpParentFullPathUri: " + tmpParentFullPathUri); | |
var fullPathUri = new Uri(fullPath); // "file:///working/directory/a/a/a/a/a/2/3" | |
Console.WriteLine("fullPathUri: " + fullPathUri); | |
var relativePathUri = tmpParentFullPathUri.MakeRelativeUri(fullPathUri); // "2/3" | |
Console.WriteLine("relativePathUri: " + relativePathUri); | |
var relativePath = relativePathUri.ToString(); // "2/3 | |
Console.WriteLine("relativePath: " + relativePath); | |
return relativePath; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment