first commit
This commit is contained in:
60
DCIT.Core/Utilities/PathUtility.cs
Normal file
60
DCIT.Core/Utilities/PathUtility.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace DCIT.Core.Utilities
|
||||
{
|
||||
public static class PathUtility
|
||||
{
|
||||
public static string NormalizeDirectory(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var fullPath = Path.GetFullPath(path.Trim());
|
||||
if (!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
|
||||
{
|
||||
fullPath += Path.DirectorySeparatorChar;
|
||||
}
|
||||
|
||||
return fullPath;
|
||||
}
|
||||
|
||||
public static bool AreSameOrNestedDirectories(string left, string right)
|
||||
{
|
||||
var normalizedLeft = NormalizeDirectory(left);
|
||||
var normalizedRight = NormalizeDirectory(right);
|
||||
if (string.IsNullOrEmpty(normalizedLeft) || string.IsNullOrEmpty(normalizedRight))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return normalizedLeft.Equals(normalizedRight, StringComparison.OrdinalIgnoreCase)
|
||||
|| normalizedLeft.StartsWith(normalizedRight, StringComparison.OrdinalIgnoreCase)
|
||||
|| normalizedRight.StartsWith(normalizedLeft, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public static string GetRelativePath(string relativeTo, string path)
|
||||
{
|
||||
var root = new Uri(NormalizeDirectory(relativeTo), UriKind.Absolute);
|
||||
var target = new Uri(Path.GetFullPath(path), UriKind.Absolute);
|
||||
var relative = root.MakeRelativeUri(target).ToString().Replace('/', Path.DirectorySeparatorChar);
|
||||
return Uri.UnescapeDataString(relative);
|
||||
}
|
||||
|
||||
public static IEnumerable<string> ValidateDirectoryPair(string firstLabel, string firstPath, string secondLabel, string secondPath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(firstPath) || string.IsNullOrWhiteSpace(secondPath))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (AreSameOrNestedDirectories(firstPath, secondPath))
|
||||
{
|
||||
yield return string.Format("{0} 与 {1} 不能相同,也不能互为父子目录。", firstLabel, secondLabel);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user