Horizon – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 using System;
2 using System.IO;
3  
4 namespace TrackedFolders.Utilities
5 {
6 /// <summary>
7 /// Various extensions for dealing with subpaths.
8 /// </summary>
9 /// <remarks>https://stackoverflow.com/questions/5617320/given-full-path-check-if-path-is-subdirectory-of-some-other-path-or-otherwise</remarks>
10 public static class Subpaths
11 {
12 #region Public Methods
13  
14 public static string NormalizePath(this string path)
15 {
16 return Path.GetFullPath(path.Replace('/', '\\')
17 .WithEnding("\\"));
18 }
19  
20 /// <summary>
21 /// Returns true if <paramref name="path" /> starts with the path <paramref name="baseDirPath" />.
22 /// The comparison is case-insensitive, handles / and \ slashes as folder separators and
23 /// only matches if the base dir folder name is matched exactly ("c:\foobar\file.txt" is not a sub path of "c:\foo").
24 /// </summary>
25 public static bool IsSubPathOf(this string path, string baseDirPath)
26 {
27 var normalizedPath = NormalizePath(path);
28  
29 var normalizedBaseDirPath = NormalizePath(baseDirPath);
30  
31 return normalizedPath.StartsWith(normalizedBaseDirPath, StringComparison.OrdinalIgnoreCase);
32 }
33  
34 public static bool IsPathEqual(this string path, string that)
35 {
36 return string.Equals(NormalizePath(path), NormalizePath(that), StringComparison.OrdinalIgnoreCase);
37 }
38  
39 #endregion
40  
41 #region Private Methods
42  
43 /// <summary>
44 /// Returns <paramref name="str" /> with the minimal concatenation of <paramref name="ending" /> (starting from end)
45 /// that
46 /// results in satisfying .EndsWith(ending).
47 /// </summary>
48 /// <example>"hel".WithEnding("llo") returns "hello", which is the result of "hel" + "lo".</example>
49 private static string WithEnding(this string str, string ending)
50 {
51 if (str == null)
52 {
53 return ending;
54 }
55  
56 var result = str;
57  
58 // Right() is 1-indexed, so include these cases
59 // * Append no characters
60 // * Append up to N characters, where N is ending length
61 for (var i = 0; i <= ending.Length; i++)
62 {
63 var tmp = result + ending.Right(i);
64 if (tmp.EndsWith(ending))
65 {
66 return tmp;
67 }
68 }
69  
70 return result;
71 }
72  
73 /// <summary>Gets the rightmost <paramref name="length" /> characters from a string.</summary>
74 /// <param name="value">The string to retrieve the substring from.</param>
75 /// <param name="length">The number of characters to retrieve.</param>
76 /// <returns>The substring.</returns>
77 private static string Right(this string value, int length)
78 {
79 if (value == null)
80 {
81 throw new ArgumentNullException("value");
82 }
83  
84 if (length < 0)
85 {
86 throw new ArgumentOutOfRangeException("length", length, "Length is less than zero");
87 }
88  
89 return length < value.Length ? value.Substring(value.Length - length) : value;
90 }
91  
92 #endregion
93 }
94 }