feat: Adding util methods for path comparisons

This commit is contained in:
Chris Cameron
2018-04-16 16:54:03 -04:00
parent ce54f953ba
commit 7065b0c567
3 changed files with 94 additions and 0 deletions

View File

@@ -10,6 +10,10 @@ namespace ICD.Common.Utils.IO
{
public static class IcdPath
{
public static char DirectorySeparatorChar { get { return Path.DirectorySeparatorChar; } }
public static char AltDirectorySeparatorChar { get { return Path.AltDirectorySeparatorChar; } }
public static string GetFileName(string path)
{
if (path == null)

View File

@@ -185,6 +185,24 @@ namespace ICD.Common.Utils
return IcdFile.Exists(path) || IcdDirectory.Exists(path);
}
/// <summary>
/// Returns the path if the given path is already a directory or has a trailing slash.
/// Otherwise returns the parent directory name.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
[PublicAPI]
public static string GetDirectoryNameFromPath(string path)
{
if (IcdDirectory.Exists(path))
return path;
if (path.EndsWith(IcdPath.DirectorySeparatorChar) || path.EndsWith(IcdPath.AltDirectorySeparatorChar))
return path;
return IcdPath.GetDirectoryName(path);
}
#endregion
}
}

View File

@@ -610,5 +610,77 @@ namespace ICD.Common.Utils
{
return value == null ? null : value.ToUpper();
}
/// <summary>
/// Compares the given chars for equality.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="ignoreCase"></param>
/// <returns></returns>
[PublicAPI]
public static bool Compare(char a, char b, bool ignoreCase)
{
if (ignoreCase)
{
a = char.ToUpper(a, CultureInfo.InvariantCulture);
b = char.ToUpper(b, CultureInfo.InvariantCulture);
}
return a == b;
}
/// <summary>
/// Find the longest common string between the matches.
/// E.g.
///
/// C:\\Workspace
/// C:\\Workshop
///
/// Results in
///
/// C:\\Work
/// </summary>
/// <param name="items"></param>
/// <param name="ignoreCase"></param>
/// <returns></returns>
[PublicAPI]
public static string GetLongestCommonIntersectionFromStart(IEnumerable<string> items, bool ignoreCase)
{
if (items == null)
throw new ArgumentNullException("items");
string output = null;
foreach (string item in items)
{
// If there is a null in the sequence that's the best match we can make
if (string.IsNullOrEmpty(item))
return null;
// Seed our first item
if (output == null)
{
output = item;
continue;
}
// Find the common substring
for (int index = 0; index < output.Length; index++)
{
if (index >= item.Length || !Compare(output[index], item[index], ignoreCase))
{
output = output.Substring(0, index);
break;
}
}
// Abandon the search if there is no common substring
if (string.IsNullOrEmpty(output))
break;
}
return output;
}
}
}