If you only want combine, there is my solution
public static string PathCombine(string pathBase, char separator = '/', params string[] paths)
{
if (paths == null || !paths.Any())
return pathBase;
#region Remove path end slash
var slash = new[] { '/', '\' };
Action<StringBuilder> removeLastSlash = null;
removeLastSlash = (sb) =>
{
if (sb.Length == 0) return;
if (!slash.Contains(sb[sb.Length - 1])) return;
sb.Remove(sb.Length - 1, 1);
removeLastSlash(sb);
};
#endregion Remove path end slash
#region Combine
var pathSb = new StringBuilder();
pathSb.Append(pathBase);
removeLastSlash(pathSb);
foreach (var path in paths)
{
pathSb.Append(separator);
pathSb.Append(path);
removeLastSlash(pathSb);
}
#endregion Combine
#region Append slash if last path contains
if (slash.Contains(paths.Last().Last()))
pathSb.Append(separator);
#endregion Append slash if last path contains
return pathSb.ToString();
}
With this, you can call
PathCombine("/path", paths: new[]{"to", "file.txt"});
// return "/path/to/file.txt"
PathCombine(@"\path", '\', "to", "file.txt");
// return @"\pathofile.txt"
PathCombine("/some/bin:paths/bin", ':', "/another/path", "/more/path");
// return "/some/bin:paths/bin:/another/path:/more/path"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…