diff --git a/SacsStandardBase/Base/Utils/StringUtil.cs b/SacsStandardBase/Base/Utils/StringUtil.cs index d10c054..26fbaad 100644 --- a/SacsStandardBase/Base/Utils/StringUtil.cs +++ b/SacsStandardBase/Base/Utils/StringUtil.cs @@ -3,6 +3,7 @@ using Sarand.Net.Standard.Base.Bus; using Sarand.Net.Standard.Base.Core; using System; using System.Globalization; +using System.IO; using System.Linq; using System.Text.RegularExpressions; @@ -332,6 +333,61 @@ namespace Sarand.Net.Standard.Base.Utils return value.Substring(0, length); } + //------------------------------------------------------------------- + /// Return the common previx for the values in the list. + public static String GetPrefix(params String[] values) + { + String prefix = values.Any() ? values[0] : ""; + foreach (String value in values) + { + // Determine how much o fthe prefix matches this value. + for (int i = 0; i < prefix.Length; i++) + { + if (value.Length <= i || value[i] != prefix[i]) + prefix = prefix.Substring(0, i); + } + } + return prefix; + } + + //------------------------------------------------------------------- + /// + /// Concatenate the partial path values, stripping leading and trailing slashes, and converting slashes (one or more in sequence) to a single path delimiter. + /// + public static String CombineFilePath(params String[] values) + { + return CombineFilePath(Path.DirectorySeparatorChar, values); + } + + /// + /// Concatenate the partial path values with forward slashes ('/'), stripping leading and trailing slashes and converting slashes (one or more in sequence) to a single forward slash. + /// + public static String CombineForwardSlashDelimited(params String[] values) + { + return CombineFilePath('/', values); + } + + /// + /// Concatenate the partial path values with the specified dlimiter, stripping leading and trailing slashes and delimiters, and converting slashes and delimiters to the required delimiter. + /// + private static String CombineFilePath(char delim, params String[] values) + { + String path = ""; + String delimPattern = "[\\\\\\/" + (delim != '\\' && delim != '/' ? "\\" + delim : "") + "]"; + foreach (String value in values) + { + if (IsBlank(path)) + // Path not yet started - being with this value. + path = value; + else + // Path is already started. + // Remove trailing delimiters from path and leading delimiters from next partial value before concatenating with path separator. + path = Regex.Replace(path, delimPattern + "+$", "") + delim.ToString() + Regex.Replace(value, "^" + delimPattern + "+", ""); + } + // Convert any combination of the alternative delimiters with requested delimiter, excluding start of path, eg. '\\share\...'. + return Regex.Replace(path, delimPattern, delim.ToString()); + } + //------------------------------------------------------------------- // C o n v e r s i o n //-------------------------------------------------------------------