During project creation, we found that the Path. Combine method can only support directory splicing in the silly way.
Copy codeThe Code is as follows: // absolute path
String absolutePath = @ "C: \ Program Files \ Internet Explorer ";
// Relative path
String relativePath = @ ".. \ TestPath \";
// Expected splicing result
String splicingResult = string. Empty;
Console. writeLine (string. format ("Path. combine (\ "{0} \", \ "{1} \") = \ "{2} \" ", absolutePath, relativePath, Path. combine (absolutePath, relativePath )));
Output result:
The relative path and absolute path are not identified as expected, so we have to use regular expressions to match the relative path for re-stitching. The following methods only support absolute path + relative path.
// Absolute path
String absolutePath = @ "C: \ Program Files \ Internet Explorer ";
// Relative path
String relativePath = @ ".. \ TestPath \";
// Expected splicing result
String splicingResult = string. Empty;
Console. writeLine (string. format ("Path. combine (\ "{0} \", \ "{1} \") = \ "{2} \" ", absolutePath, relativePath, Path. combine (absolutePath, relativePath )));
If (! Path. IsPathRooted (relativePath ))
{
// Match the relative path and the number of directory layers to be pushed up
Regex regex = new Regex (@ "^ \ | ([..] + )");
Int backUp = regex. Matches (relativePath). Count;
List <string> pathes = absolutePath. Split ("\". ToCharArray (). ToList ();
Pathes. RemoveRange (pathes. Count-backUp, backUp );
// Match the file name, matching the number of directories to be appended
Regex = new Regex (@ "^ \ | ([a-zA-Z0-9] + )");
MatchCollection matches = regex. Matches (relativePath );
Foreach (Match match in matches)
{
Pathes. Add (match. Value );
}
// Obtain the drive address from the absolute path.
Pathes [0] = Path. GetPathRoot (absolutePath );
Foreach (string p in pathes)
{
SplicingResult = Path. Combine (splicingResult, p );
}
}
Console. WriteLine (string. Format ("Absolute Path = {0}", absolutePath ));
Console. WriteLine (string. Format ("Relative Path = {0}", relativePath ));
Console. writeLine (string. format ("Path. combine (\ "{0} \", \ "{1} \") = \ "{2} \" ", absolutePath, relativePath, splicingResult ));
Console. ReadLine ();
Output result: