Учитывая полный путь, проверьте, является ли путь подкаталогом какого-либо другого пути или иным образом
У меня есть 2 строки - dir1 и dir2, и мне нужно проверить, является ли это подкаталогом для другого. Я попытался использовать метод Contains:
dir1.contains(dir2);
но это также возвращает true, если каталоги имеют похожие имена, например: c:\abc и c:\abc1 не являются подкаталогами, ставка возвращает true. Должен быть лучший способ.
Ответы
Ответ 1
DirectoryInfo di1 = new DirectoryInfo(dir1);
DirectoryInfo di2 = new DirectoryInfo(dir2);
bool isParent = di2.Parent.FullName == di1.FullName;
Или в цикле, чтобы разрешить вложенные подкаталоги, то есть C:\foo\bar\baz - это подкаталог C:\foo:
DirectoryInfo di1 = new DirectoryInfo(dir1);
DirectoryInfo di2 = new DirectoryInfo(dir2);
bool isParent = false;
while (di2.Parent != null)
{
if (di2.Parent.FullName == di1.FullName)
{
isParent = true;
break;
}
else di2 = di2.Parent;
}
Ответ 2
- Нечувствительность к регистру
- Толерантное сочетание
\
и /
разделителей папок
- Толеранты
..\
в пути
- Предотвращает совпадение имен парных папок (
c:\foobar
не подпуть c:\foo
)
Примечание. Это только соответствует строке пути и не работает для символических ссылок и других видов ссылок в файловой системе.
Код:
public static class StringExtensions
{
/// <summary>
/// Returns true if <paramref name="path"/> starts with the path <paramref name="baseDirPath"/>.
/// The comparison is case-insensitive, handles / and \ slashes as folder separators and
/// only matches if the base dir folder name is matched exactly ("c:\foobar\file.txt" is not a sub path of "c:\foo").
/// </summary>
public static bool IsSubPathOf(this string path, string baseDirPath)
{
string normalizedPath = Path.GetFullPath(path.Replace('/', '\\')
.WithEnding("\\"));
string normalizedBaseDirPath = Path.GetFullPath(baseDirPath.Replace('/', '\\')
.WithEnding("\\"));
return normalizedPath.StartsWith(normalizedBaseDirPath, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Returns <paramref name="str"/> with the minimal concatenation of <paramref name="ending"/> (starting from end) that
/// results in satisfying .EndsWith(ending).
/// </summary>
/// <example>"hel".WithEnding("llo") returns "hello", which is the result of "hel" + "lo".</example>
public static string WithEnding([CanBeNull] this string str, string ending)
{
if (str == null)
return ending;
string result = str;
// Right() is 1-indexed, so include these cases
// * Append no characters
// * Append up to N characters, where N is ending length
for (int i = 0; i <= ending.Length; i++)
{
string tmp = result + ending.Right(i);
if (tmp.EndsWith(ending))
return tmp;
}
return result;
}
/// <summary>Gets the rightmost <paramref name="length" /> characters from a string.</summary>
/// <param name="value">The string to retrieve the substring from.</param>
/// <param name="length">The number of characters to retrieve.</param>
/// <returns>The substring.</returns>
public static string Right([NotNull] this string value, int length)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (length < 0)
{
throw new ArgumentOutOfRangeException("length", length, "Length is less than zero");
}
return (length < value.Length) ? value.Substring(value.Length - length) : value;
}
}
Тестовые примеры (NUnit):
[TestFixture]
public class StringExtensionsTest
{
[TestCase(@"c:\foo", @"c:", Result = true)]
[TestCase(@"c:\foo", @"c:\", Result = true)]
[TestCase(@"c:\foo", @"c:\foo", Result = true)]
[TestCase(@"c:\foo", @"c:\foo\", Result = true)]
[TestCase(@"c:\foo\", @"c:\foo", Result = true)]
[TestCase(@"c:\foo\bar\", @"c:\foo\", Result = true)]
[TestCase(@"c:\foo\bar", @"c:\foo\", Result = true)]
[TestCase(@"c:\foo\a.txt", @"c:\foo", Result = true)]
[TestCase(@"c:\FOO\a.txt", @"c:\foo", Result = true)]
[TestCase(@"c:/foo/a.txt", @"c:\foo", Result = true)]
[TestCase(@"c:\foobar", @"c:\foo", Result = false)]
[TestCase(@"c:\foobar\a.txt", @"c:\foo", Result = false)]
[TestCase(@"c:\foobar\a.txt", @"c:\foo\", Result = false)]
[TestCase(@"c:\foo\a.txt", @"c:\foobar", Result = false)]
[TestCase(@"c:\foo\a.txt", @"c:\foobar\", Result = false)]
[TestCase(@"c:\foo\..\bar\baz", @"c:\foo", Result = false)]
[TestCase(@"c:\foo\..\bar\baz", @"c:\bar", Result = true)]
[TestCase(@"c:\foo\..\bar\baz", @"c:\barr", Result = false)]
public bool IsSubPathOfTest(string path, string baseDirPath)
{
return path.IsSubPathOf(baseDirPath);
}
}
Обновление
- 2015-08-18: Исправьте ошибку в именах парных папок. Добавьте тестовые примеры.
- 2015-09-02: поддержка
..\
в путях, добавление недостающего кода
- 2017-09-06: добавьте примечание к символическим ссылкам.
Ответ 3
Try:
dir1.contains(dir2+"\\");
Ответ 4
Мои пути могут содержать разные оболочки и даже иметь необрезанные сегменты...
Кажется, что это работает:
public static bool IsParent(string fullPath, string base)
{
var fullPathSegments = SegmentizePath(fullPath);
var baseSegments = SegmentizePath(base);
var index = 0;
while (fullPathSegments.Count>index && baseSegments.Count>index &&
fullPathSegments[index].Trim().ToLower() == baseSegments[index].Trim().ToLower())
index++;
return index==baseSegments.Count-1;
}
public static IList<string> SegmentizePath(string path)
{
var segments = new List<string>();
var remaining = new DirectoryInfo(path);
while (null != remaining)
{
segments.Add(remaining.Name);
remaining = remaining.Parent;
}
segments.Reverse();
return segments;
}
Ответ 5
Исходя из ответа @BrokenGlass, но настроенного:
using System.IO;
internal static class DirectoryInfoExt
{
internal static bool IsSubDirectoryOfOrSame(this DirectoryInfo directoryInfo, DirectoryInfo potentialParent)
{
if (DirectoryInfoComparer.Default.Equals(directoryInfo, potentialParent))
{
return true;
}
return IsStrictSubDirectoryOf(directoryInfo, potentialParent);
}
internal static bool IsStrictSubDirectoryOf(this DirectoryInfo directoryInfo, DirectoryInfo potentialParent)
{
while (directoryInfo.Parent != null)
{
if (DirectoryInfoComparer.Default.Equals(directoryInfo.Parent, potentialParent))
{
return true;
}
directoryInfo = directoryInfo.Parent;
}
return false;
}
}
using System;
using System.Collections.Generic;
using System.IO;
public class DirectoryInfoComparer : IEqualityComparer<DirectoryInfo>
{
private static readonly char[] TrimEnd = { '\\' };
public static readonly DirectoryInfoComparer Default = new DirectoryInfoComparer();
private static readonly StringComparer OrdinalIgnoreCaseComparer = StringComparer.OrdinalIgnoreCase;
private DirectoryInfoComparer()
{
}
public bool Equals(DirectoryInfo x, DirectoryInfo y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x == null || y == null)
{
return false;
}
return OrdinalIgnoreCaseComparer.Equals(x.FullName.TrimEnd(TrimEnd), y.FullName.TrimEnd(TrimEnd));
}
public int GetHashCode(DirectoryInfo obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
return OrdinalIgnoreCaseComparer.GetHashCode(obj.FullName.TrimEnd(TrimEnd));
}
}
Не идеально, если производительность важна.
Ответ 6
Обновление - это я написал изначально неправильно (см. ниже):
Мне кажется, что вы действительно придерживаетесь базового сравнения строк (конечно, используя .ToLower()), используя функцию .StartsWith(), а также подсчитывая разделители путей, но вы добавляете дополнительное рассмотрение в отношении количество разделителей путей - и вам нужно заранее использовать что-то вроде Path.GetFullPath() в строках, чтобы убедиться, что вы имеете дело с согласованными форматами строки пути. Таким образом, вы получите что-то основное и простое, например:
string dir1a = Path.GetFullPath(dir1).ToLower();
string dir2a = Path.GetFullPath(dir2).ToLower();
if (dir1a.StartsWith(dir2a) || dir2a.StartsWith(dir1a)) {
if (dir1a.Count(x => x = Path.PathSeparator) != dir2a.Count(x => x = Path.PathSeparator)) {
// one path is inside the other path
}
}
Обновление...
Как я обнаружил при использовании моего кода, причина в том, что это неправильно, потому что он не учитывает случаи, когда одно имя каталога начинается с тех же символов, что и полное имя другого каталога. У меня был случай, когда у меня был один путь к каталогу "D:\prog\dat\Mirror_SourceFiles" и другой путь к папке "D:\prog\dat\Mirror". Поскольку мой первый путь действительно "начинается с" букв "D:\prog\dat\Mirror", мой код дал мне ложное совпадение. Я избавился от .StartsWith полностью и изменил код на это (метод: разделите путь на отдельные части и сравните детали с меньшим количеством частей):
// make sure "dir1" and "dir2a" are distinct from each other
// (i.e., not the same, and neither is a subdirectory of the other)
string[] arr_dir1 = Path.GetFullPath(dir1).Split(Path.DirectorySeparatorChar);
string[] arr_dir2 = Path.GetFullPath(dir2).Split(Path.DirectorySeparatorChar);
bool bSame = true;
int imax = Math.Min(arr_dir1.Length, arr_dir2.Length);
for (int i = 0; i < imax; ++i) {
if (String.Compare(arr_dir1[i], arr_dir2[i], true) != 0) {
bSame = false;
break;
}
}
if (bSame) {
// do what you want to do if one path is the same or
// a subdirectory of the other path
}
else {
// do what you want to do if the paths are distinct
}
Конечно, обратите внимание, что в "реальной программе" вы собираетесь использовать функцию Path.GetFullPath() в try-catch для обработки соответствующих исключений в отношении строки, которую вы передаете в нее.
Ответ 7
В моем случае путь и возможный подпуть не содержат ".." и никогда не заканчиваются на "\":
private static bool IsSubpathOf(string path, string subpath)
{
return (subpath.Equals(path, StringComparison.OrdinalIgnoreCase) ||
subpath.StartsWith(path + @"\", StringComparison.OrdinalIgnoreCase));
}
Ответ 8
public static bool IsSubpathOf(string rootPath, string subpath)
{
if (string.IsNullOrEmpty(rootPath))
throw new ArgumentNullException("rootPath");
if (string.IsNullOrEmpty(subpath))
throw new ArgumentNulLException("subpath");
Contract.EndContractBlock();
return subath.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase);
}