-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPathUtilities.cs
More file actions
1158 lines (714 loc) · 37.7 KB
/
PathUtilities.cs
File metadata and controls
1158 lines (714 loc) · 37.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Gsemac.IO.Properties;
using Gsemac.Text;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Gsemac.IO {
public delegate string CharReplacementEvaluatorDelegate(char inputChar);
public static class PathUtilities {
// Public members
public const int MaxFilePathLength = 259; // 260 minus 1 for '\0'
public const int MaxDirectoryPathLength = 247; // 248 minus 1 for '\0'
public const int MaxPathSegmentLength = 255;
public const string ExtendedLengthPrefix = @"\\?\";
public static string GetPath(string path) {
return GetPath(path, PathInfo.Default);
}
public static string GetPath(string path, IPathInfo pathInfo) {
if (pathInfo is null)
throw new ArgumentNullException(nameof(pathInfo));
string relativePath = path;
if (!string.IsNullOrWhiteSpace(relativePath))
relativePath = path.Substring(GetRootPath(path).Length);
if ((pathInfo.IsUrl ?? false) || IsUrl(path)) {
// Strip query and fragment strings.
relativePath = StringUtilities.BeforeLast(StringUtilities.BeforeLast(relativePath, "?"), "#");
}
else {
relativePath = TrimLeftDirectorySeparators(relativePath);
}
return relativePath;
}
public static IEnumerable<string> GetPathSegments(string path) {
// Get the root of the path first, as it might contain multiple directory separators.
string pathRoot = GetRootPath(path);
if (!string.IsNullOrEmpty(pathRoot)) {
path = path.Substring(pathRoot.Length);
// On Windows, GetPathRoot can return just a drive letter (e.g. "C:"). To signify that this is a path, append a directory separator.
// The separator is not always appended, because it might be a single separator (e.g. "/") on Unix systems.
if (StartsWithDirectorySeparatorChar(path) && !EndsWithDirectorySeparatorChar(pathRoot)) {
pathRoot += path.First();
path = path.Substring(1);
}
yield return pathRoot;
}
// Return the remaining segments.
IEnumerable<string> remainingSegments = StringUtilities.Split(path, new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, new StringSplitOptionsEx() {
SplitAfterDelimiter = true,
}).Where(segment => !string.IsNullOrEmpty(segment));
foreach (string segment in remainingSegments)
yield return segment;
}
public static string GetRelativePath(string path, string basePath) {
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
if (string.IsNullOrEmpty(basePath))
return path;
string fullInputPath = Path.GetFullPath(path);
string fullRelativeToPath = TrimDirectorySeparators(Path.GetFullPath(basePath)) + Path.DirectorySeparatorChar;
int index = fullInputPath.IndexOf(fullRelativeToPath);
if (index >= 0)
return fullInputPath.Substring(index + fullRelativeToPath.Length, fullInputPath.Length - (index + fullRelativeToPath.Length));
else
return path;
}
public static string GetRootPath(string path) {
return GetRootPath(path, PathInfo.Default);
}
public static string GetRootPath(string path, IPathInfo pathInfo) {
if (pathInfo is null)
throw new ArgumentNullException(nameof(pathInfo));
string rootPath = string.Empty;
string scheme = GetScheme(path);
if (!string.IsNullOrWhiteSpace(scheme)) {
Match rootMatch = Regex.Match(path.Substring(scheme.Length), @":[\/\\]{2}[^\/\\]+(?:[\/\\]|$)");
if (rootMatch.Success)
rootPath = path.Substring(0, scheme.Length + rootMatch.Length);
}
else if (!string.IsNullOrEmpty(path)) {
// If the path starts with a single slash, consider that to be the root.
// Don't consider the path rooted if it's a URL that starts with a forward slash (it's relative).
if (!(IsUrl(path, pathInfo) && (path.StartsWith("/") || path.StartsWith("\\")))) {
Match rootMatch = Regex.Match(path, @"^([\/\\]{1})[^\/\\]");
if (rootMatch.Success)
rootPath = rootMatch.Groups[1].Value;
else
rootPath = Path.GetPathRoot(path);
}
}
if (!string.IsNullOrEmpty(rootPath) && !rootPath.All(c => c.Equals(Path.DirectorySeparatorChar) || c.Equals(Path.AltDirectorySeparatorChar)))
rootPath = TrimRightDirectorySeparators(rootPath);
return rootPath;
}
public static string GetParentPath(string path) {
return GetParentPath(path, PathInfo.Default);
}
public static string GetParentPath(string path, IPathInfo pathInfo) {
if (pathInfo is null)
throw new ArgumentNullException(nameof(pathInfo));
if (string.IsNullOrWhiteSpace(path))
return string.Empty;
string rootPath = GetRootPath(path, pathInfo);
int separatorIndex = TrimRightDirectorySeparators(path).LastIndexOfAny(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
if (separatorIndex < rootPath.Length)
return string.Empty;
return path.Substring(0, separatorIndex);
}
public static int GetPathDepth(string path) {
return GetPathDepth(path, PathDepthOptions.Default);
}
public static int GetPathDepth(string path, IPathDepthOptions options) {
if (options is null)
throw new ArgumentNullException(nameof(options));
if (string.IsNullOrWhiteSpace(path))
return 0;
path = NormalizeDirectorySeparators(TrimLeftDirectorySeparators(GetPath(path)));
if (options.IgnoreTrailingDirectorySeparators)
path = TrimRightDirectorySeparators(path);
if (string.IsNullOrWhiteSpace(path))
return 0;
return path.Split(new[] { Path.DirectorySeparatorChar }).Count();
}
public static string GetScheme(string path) {
path = path?.Trim() ?? string.Empty;
Match match = Regex.Match(path, @"^(?<scheme>[\w][\w+-.]+):");
if (match.Success)
return match.Groups["scheme"].Value;
return string.Empty;
}
public static string SetScheme(string path, string scheme) {
path = path?.Trim() ?? string.Empty;
string schemePart;
if (!string.IsNullOrWhiteSpace(scheme)) {
schemePart = $"{scheme.Trim()}://";
}
else {
// If the scheme is empty, we'll use a relative scheme.
schemePart = "//";
}
Regex regex = new Regex(@"^(?:[\w][\w+-.]+:)?(?:\/\/)?");
return regex.Replace(path, schemePart, 1);
}
public static string GetFileName(string path) {
return GetFileName(path, PathInfo.Default);
}
public static string GetFileName(string path, IPathInfo pathInfo) {
if (pathInfo is null)
throw new ArgumentNullException(nameof(pathInfo));
// This process should work for both remote and local paths.
// The user is optionally able to specify explicitly whether the path is a URL or a local path.
if (IsUrl(path, pathInfo))
return GetFileNameFromUrl(path);
// If the path cannot be determined to be a URL, treat it like a local path.
// Invalid path characters are be allowed (e.g. "|"), and content after the hash character ("#") should be included in the filename.
// While this signifies the start of a URI fragment for URLs, it is a valid path character on Windows and most Linux flavors.
return GetFileNameWithRegex(path, IsUrl(path, pathInfo));
}
public static string GetFileNameWithoutExtension(string path) {
string fileName = GetFileName(path);
return StringUtilities.BeforeLast(fileName, ".");
}
public static string GetFileExtension(string path) {
string filename = GetFileName(path);
if (string.IsNullOrWhiteSpace(filename))
return string.Empty;
else
return Path.GetExtension(ReplaceInvalidPathChars(filename, SanitizePathOptions.Default));
}
public static string SetFileExtension(string path, string extension) {
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(extension));
if (!IsFilePath(path, verifyFileExists: false))
throw new ArgumentException(string.Format(ExceptionMessages.PathIsNotFilePath, path));
extension = extension?.Trim();
if (!string.IsNullOrWhiteSpace(extension) && !extension.StartsWith("."))
extension = "." + extension;
string oldExtension = GetFileExtension(path);
if (!string.IsNullOrEmpty(oldExtension)) {
// The path already has a file extension, so replace the old extension.
path = StringUtilities.ReplaceLast(path, oldExtension, extension);
}
else {
// The path does not have a file extension, so we'll just append the new extension.
path += extension;
}
return path;
}
public static string NormalizeFileExtension(string extension) {
if (extension is null)
throw new ArgumentNullException(nameof(extension));
if (string.IsNullOrWhiteSpace(extension))
throw new ArgumentException(Properties.ExceptionMessages.InvalidFileExtension, nameof(extension));
extension = extension.ToLowerInvariant()
.Trim('.')
.Trim();
extension = "." + extension;
return extension;
}
public static bool HasFileExtension(string path) {
if (string.IsNullOrWhiteSpace(path))
return false;
return !string.IsNullOrWhiteSpace(GetFileExtension(path));
}
public static long GetSize(string path) {
if (TryGetSize(path, out long size))
return size;
return 0;
}
public static bool TryGetSize(string path, out long size) {
size = 0;
if (string.IsNullOrWhiteSpace(path))
return false;
if (File.Exists(path) && FileUtilities.TryGetSize(path, out size))
return true;
if (Directory.Exists(path) && DirectoryUtilities.TryGetSize(path, out size))
return true;
return false;
}
public static string GetTemporaryDirectoryPath() {
return GetTemporaryDirectoryPath(TemporaryPathOptions.Default);
}
public static string GetTemporaryDirectoryPath(ITemporaryPathOptions options) {
if (options is null)
throw new ArgumentNullException(nameof(options));
if (!options.EnsureUnique)
return GetTemporaryFilePath(options);
lock (uniquePathMutex) {
string result;
// Theoretically, this could result in an infinite loop. But that won't happen... Right?
do {
// "EnsureUnique" is set to false so that a file isn't created, which would prevent us from creating the directory.
result = GetTemporaryFilePath(new TemporaryPathOptions() {
EnsureUnique = false,
});
} while (Directory.Exists(result));
Directory.CreateDirectory(result);
return result;
}
}
public static string GetTemporaryFilePath() {
return GetTemporaryFilePath(TemporaryPathOptions.Default);
}
public static string GetTemporaryFilePath(ITemporaryPathOptions options) {
if (options is null)
throw new ArgumentNullException(nameof(options));
return options.EnsureUnique ?
Path.GetTempFileName() :
Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
}
public static bool IsTemporaryFilePath(string path) {
bool isTemporaryFilePath = false;
try {
path = Path.GetFullPath(path);
isTemporaryFilePath = path.StartsWith(Path.GetTempPath()) && IsFilePath(path);
}
catch (Exception) {
// If the path is not a valid path, then it definitely isn't a temporary file path.
}
return isTemporaryFilePath;
}
public static bool IsUrl(string path) {
if (string.IsNullOrWhiteSpace(path))
return false;
return !string.IsNullOrWhiteSpace(GetScheme(path));
}
public static bool IsUrl(string path, IPathInfo pathInfo) {
if (pathInfo is null)
throw new ArgumentNullException(nameof(pathInfo));
if (pathInfo.IsUrl.HasValue)
return pathInfo.IsUrl.Value;
return IsUrl(path);
}
public static string AnonymizePath(string path) {
// Remove the current user's username from the path (if the path is inside the user directory).
string userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
if (!string.IsNullOrWhiteSpace(userDirectory) && !string.IsNullOrWhiteSpace(path)) {
// Make the paths relative to their root so that the path can be anonymized regardless of the drive it's on.
userDirectory = GetPath(userDirectory);
path = GetPath(path);
if (path.StartsWith(userDirectory)) {
// If the path is directly inside of %USERPROFILE%, make the path relative to that variable.
path = Path.Combine("%USERPROFILE%", GetRelativePath(path, userDirectory));
}
}
return path;
}
public static string SanitizePath(string path) {
return SanitizePath(path, SanitizePathOptions.Default);
}
public static string SanitizePath(string path, ISanitizePathOptions options) {
if (options is null)
throw new ArgumentNullException(nameof(options));
if (options.UseEquivalentValidPathChars) {
bool inQuotes = false;
return SanitizePath(path, c => GetEquivalentValidPathChar(c, ref inQuotes), options);
}
else {
return SanitizePath(path, string.Empty, options);
}
}
public static string SanitizePath(string path, string replacement) {
return SanitizePath(path, replacement, SanitizePathOptions.Default);
}
public static string SanitizePath(string path, string replacement, ISanitizePathOptions options) {
if (options is null)
throw new ArgumentNullException(nameof(options));
return SanitizePath(path, c => replacement, options);
}
public static string SanitizePath(string path, CharReplacementEvaluatorDelegate replacementEvaluator) {
if (replacementEvaluator is null)
throw new ArgumentNullException(nameof(replacementEvaluator));
return SanitizePath(path, replacementEvaluator, SanitizePathOptions.Default);
}
public static string SanitizePath(string path, CharReplacementEvaluatorDelegate replacementEvaluator, ISanitizePathOptions options) {
if (replacementEvaluator is null)
throw new ArgumentNullException(nameof(replacementEvaluator));
if (options is null)
throw new ArgumentNullException(nameof(options));
return ReplaceInvalidPathChars(path, replacementEvaluator, options);
}
public static string TrimDirectorySeparators(string path) {
return path?.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
public static string TrimLeftDirectorySeparators(string path) {
return path?.TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
public static string TrimRightDirectorySeparators(string path) {
return path?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
public static string NormalizeDirectorySeparators(string path) {
return NormalizeDirectorySeparators(path, PathInfo.Default);
}
public static string NormalizeDirectorySeparators(string path, char directorySeparatorChar) {
path = string.Join(directorySeparatorChar.ToString(),
path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
return path;
}
public static string NormalizeDirectorySeparators(string path, IPathInfo pathInfo) {
if (pathInfo is null)
throw new ArgumentNullException(nameof(pathInfo));
if (string.IsNullOrEmpty(path))
return path;
char directorySeparatorChar = Path.DirectorySeparatorChar;
if (IsUrl(path, pathInfo))
directorySeparatorChar = '/';
return NormalizeDirectorySeparators(path, directorySeparatorChar);
}
public static bool IsDirectorySeparator(char value) {
return IsDirectorySeparator(value.ToString(CultureInfo.InvariantCulture));
}
public static bool IsDirectorySeparator(string value) {
return value.Equals(Path.DirectorySeparatorChar) ||
value.Equals(Path.AltDirectorySeparatorChar);
}
public static string NormalizeDotSegments(string path) {
return NormalizeDotSegments(path, PathInfo.Default);
}
public static string NormalizeDotSegments(string path, IPathInfo pathInfo) {
if (pathInfo is null)
throw new ArgumentNullException(nameof(pathInfo));
if (string.IsNullOrWhiteSpace(path))
return path;
string currentPathSegmentStr1 = "." + Path.DirectorySeparatorChar;
string currentPathSegmentStr2 = "." + Path.AltDirectorySeparatorChar;
string parentPathSegmentStr1 = ".." + Path.DirectorySeparatorChar;
string parentPathSegmentStr2 = ".." + Path.AltDirectorySeparatorChar;
bool isPathRooted = IsPathRooted(path, pathInfo);
Stack<string> segments = new Stack<string>();
foreach (string segment in GetPathSegments(path)) {
if (segment.Equals(currentPathSegmentStr1) || segment.Equals(currentPathSegmentStr2))
continue;
if (segment.Equals(parentPathSegmentStr1) || segment.Equals(parentPathSegmentStr2)) {
// Don't allow the root of the path to be popped off.
if (segments.Count > 0 && (segments.Count > 1 || !isPathRooted))
segments.Pop();
}
else {
segments.Push(segment);
}
}
// Reverse the segments before joining, because iterating through a stack takes us from top to bottom.
return string.Join(string.Empty, segments.Reverse());
}
public static bool IsFilePath(string path, bool verifyFileExists = false) {
bool result = path.Any() &&
path.Last() != Path.DirectorySeparatorChar &&
path.Last() != Path.AltDirectorySeparatorChar;
if (verifyFileExists && result)
result = File.Exists(path);
return result;
}
public static bool IsLocalPath(string path, bool verifyPathExists = false) {
bool isLocalPath = false;
if (!string.IsNullOrEmpty(path)) {
// Remove the extended length prefix if it is present. If it is present, "Uri.TryCreate" will fail.
// Since we're not creating any files, we don't need to worry about it.
if (path.StartsWith(ExtendedLengthPrefix))
path = path.Substring(ExtendedLengthPrefix.Length);
if (Uri.TryCreate(path, UriKind.Absolute, out Uri testUri)) {
// "IsFile" returns true for both local file and directory paths.
// "IsUnc" will return true for paths beginning with "\\" or "//" (the latter case gets turned into "file://").
isLocalPath = testUri.IsFile && !testUri.IsUnc &&
(!verifyPathExists || PathExists(testUri.LocalPath));
}
else if (new char[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar }.Any(c => c == path.First())) {
// Rooted paths that don't specify a scheme will be considered local.
isLocalPath = !verifyPathExists || PathExists(testUri.LocalPath);
}
else if (Uri.TryCreate(path, UriKind.Relative, out _)) {
// Check the full path for this relative path.
path = Path.GetFullPath(path);
isLocalPath = IsLocalPath(path, verifyPathExists: verifyPathExists);
}
}
return isLocalPath;
}
public static bool IsPathRooted(string path) {
return IsPathRooted(path, PathInfo.Default);
}
public static bool IsPathRooted(string path, IPathInfo pathInfo) {
if (pathInfo is null)
throw new ArgumentNullException(nameof(pathInfo));
// "System.IO.Path.IsPathRooted" throws an exception for paths longer than the maximum path length, as well as for malformed paths (e.g. paths containing invalid characters).
// URLs starting with path separators are not rooted, but relative to the root.
if (IsUrl(path, pathInfo) && (path.StartsWith("/") || path.StartsWith("\\")))
return false;
string directorySeparatorsStr = Path.DirectorySeparatorChar.ToString() + Path.AltDirectorySeparatorChar.ToString();
string pattern = @"^(?:[" + Regex.Escape(directorySeparatorsStr) + @"]|[a-z]+\:\/\/|[a-z]\:)";
return Regex.IsMatch(path, pattern, RegexOptions.IgnoreCase);
}
public static bool IsPathTooLong(string path) {
// For the purpose of checking the length, replace all illegal characters in the path.
// This will ensure Path methods don't throw.
path = ReplaceInvalidPathChars(path, " ", new SanitizePathOptions() {
PreserveDirectoryStructure = true,
});
path = Path.GetFullPath(path);
// Check the length of the entire path.
if (IsFilePath(path, false)) {
if (Path.GetDirectoryName(path).Length > MaxDirectoryPathLength || path.Length > MaxFilePathLength)
return true;
}
else {
path = TrimDirectorySeparators(path);
if (path.Length > MaxDirectoryPathLength)
return true;
}
// Check the length of each segment.
if (GetPathSegments(path).Any(segment => TrimDirectorySeparators(segment).Length > MaxPathSegmentLength))
return true;
return false;
}
public static bool IsSubpathOf(string parentPath, string childPath) {
if (string.IsNullOrWhiteSpace(parentPath) || string.IsNullOrWhiteSpace(childPath))
return false;
if (!IsPathRooted(parentPath))
parentPath = Path.GetFullPath(parentPath);
if (!IsPathRooted(childPath))
childPath = Path.GetFullPath(childPath);
parentPath = NormalizeDirectorySeparators(TrimRightDirectorySeparators(parentPath) + "/");
childPath = NormalizeDirectorySeparators(TrimRightDirectorySeparators(childPath) + "/");
return !AreEqual(parentPath, childPath) &&
childPath.StartsWith(parentPath);
}
public static bool PathExists(string path) {
return Directory.Exists(path) || File.Exists(path);
}
public static bool PathContainsSegment(string path, string pathSegment) {
pathSegment = TrimDirectorySeparators(pathSegment);
return GetPathSegments(path)
.Select(segment => TrimDirectorySeparators(segment))
.Any(segment => segment.Equals(pathSegment, StringComparison.OrdinalIgnoreCase));
}
public static bool AreEqual(string path1, string path2) {
return AreEqual(path1, path2, StringComparison.OrdinalIgnoreCase);
}
public static bool AreEqual(string path1, string path2, StringComparison stringComparison) {
// This is intended to be a simple comparison between two paths that disregards equivalent path separators.
// For a more robust approach that considers full path equivalency, use the "AreEquivalent" method.
// On both Windows and Unix-based systems, trailing directory separators are irrelevant.
// Trailing directory separators are typically used to denote directory paths, but we cannot have a directory and file with the same name.
// For this reason, the two paths must be equivalent to each other.
// https://unix.stackexchange.com/q/22447
// URLs with trailing slashes are not treated the same as local paths with trailing slashes.
// It's up to the web server to decide how to interpret them, and there are certainly cases where the two paths are not equivalent to each other.
// https://stackoverflow.com/q/942751
if (!IsUrl(path1))
path1 = path1?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (!IsUrl(path2))
path2 = path2?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// If the paths are both empty, consider the paths to be equal.
if (string.IsNullOrWhiteSpace(path1) && string.IsNullOrWhiteSpace(path2))
return true;
// If only one of the paths is empty, the paths are not equal.
if (string.IsNullOrWhiteSpace(path1) || string.IsNullOrWhiteSpace(path2))
return false;
// On Windows systems, we should normalize directory separators because "/" and "\" are equivalent.
// However, on Unix systems and in URLs, the only valid directory separator is "/". Should we account for this?
path1 = NormalizeDirectorySeparators(path1);
path2 = NormalizeDirectorySeparators(path2);
return path1.Equals(path2, stringComparison);
}
public static bool AreEquivalent(string path1, string path2) {
return AreEquivalent(path1, path2, StringComparison.OrdinalIgnoreCase);
}
public static bool AreEquivalent(string path1, string path2, StringComparison stringComparison) {
// Extra slashes after the scheme are stripped by major web browsers and clients, so the two paths should point to the same location.
// This isn't technically correct, but is common enough behavior that most clients implement it.
// https://github.com/curl/curl/issues/791
if (IsUrl(path1))
path1 = StripRepeatedForwardSlashesAfterScheme(path1);
if (IsUrl(path2))
path2 = StripRepeatedForwardSlashesAfterScheme(path2);
// If the two paths are equal, consider them to also be equivalent.
if (AreEqual(path1, path2, stringComparison))
return true;
// To decide if two paths are equivalent, we need to fully expand them.
// It's possible for "GetFullPath" to throw if we pass in an invalid path.
// If it throws for either path, consider them not to be equivalent.
try {
path1 = Path.GetFullPath(path1);
path2 = Path.GetFullPath(path2);
return AreEqual(path1, path2, stringComparison);
}
catch (Exception) {
return false;
}
}
// Private members
private static readonly object uniquePathMutex = new object();
private static bool EndsWithDirectorySeparatorChar(string path) {
return !string.IsNullOrEmpty(path) &&
(path.EndsWith(Path.DirectorySeparatorChar.ToString()) ||
path.EndsWith(Path.AltDirectorySeparatorChar.ToString()));
}
private static string ReplaceInvalidPathChars(string path, ISanitizePathOptions options) {
if (options is null)
throw new ArgumentNullException(nameof(options));
return ReplaceInvalidPathChars(path, string.Empty, options);
}
private static string ReplaceInvalidPathChars(string path, string replacement, ISanitizePathOptions options) {
if (options is null)
throw new ArgumentNullException(nameof(options));
return ReplaceInvalidPathChars(path, c => replacement, options);
}
private static string ReplaceInvalidPathChars(string path, CharReplacementEvaluatorDelegate replacementEvaluator, ISanitizePathOptions options) {
if (replacementEvaluator is null)
throw new ArgumentNullException(nameof(replacementEvaluator));
if (options is null)
throw new ArgumentNullException(nameof(options));
string rootOrScheme = string.Empty;
IEnumerable<char> invalidCharacters = Enumerable.Empty<char>();
// To match the behavior of popular web browsers, trim excess forward slashes after the scheme when using HTTP/HTTPS.
// https://github.com/whatwg/url/issues/118
// This is only done when the "PreserveDirectoryStructure" flag is toggled, because otherwise the slashes are replaced anyway (as may be desired).
if (options.PreserveDirectoryStructure)
StripRepeatedForwardSlashesAfterScheme(path);
// Normalize directory separators.
if (options.NormalizeDirectorySeparators)
path = NormalizeDirectorySeparators(path);
if (options.StripInvalidPathChars)
invalidCharacters = invalidCharacters.Concat(Path.GetInvalidPathChars());
if (options.StripInvalidFileNameChars)
invalidCharacters = invalidCharacters.Concat(Path.GetInvalidFileNameChars());
if (options.PreserveDirectoryStructure) {
// The root of the path might contain characters that would be invalid file name characters (e.g. ':' in "C:\").
// In order to preserve the root path information, we'll remove it for now and add it back later.
rootOrScheme = GetRootOrScheme(path);
if (!string.IsNullOrEmpty(rootOrScheme))
path = path.Substring(rootOrScheme.Length);
invalidCharacters = invalidCharacters.Where(c => c != Path.DirectorySeparatorChar && c != Path.AltDirectorySeparatorChar);
}
// Strip repeated directory separators.
if (options.StripRepeatedDirectorySeparators)
StripRepeatedDirectorySeparators(path);
HashSet<char> invalidCharacterLookup = new HashSet<char>(invalidCharacters);
StringBuilder pathBuilder = new StringBuilder();
foreach (char c in path.ToCharArray()) {
if (invalidCharacterLookup.Contains(c))
pathBuilder.Append(replacementEvaluator(c));
else
pathBuilder.Append(c);
}
path = pathBuilder.ToString();
if (!string.IsNullOrEmpty(rootOrScheme))
path = rootOrScheme + TrimLeftDirectorySeparators(path);
return path;
}
private static string GetEquivalentValidPathChar(char inputChar, ref bool inQuotes) {
switch (inputChar) {
case '\0':
case '\u0001':
case '\u0002':
case '\u0003':
case '\u0004':
case '\u0005':
case '\u0006':
case '\a':
case '\b':
case '\n':
case '\v':
case '\f':