Path.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. #if MS_IO_REDIST
  8. using System;
  9. using System.IO;
  10. namespace Microsoft.IO
  11. #else
  12. namespace System.IO
  13. #endif
  14. {
  15. // Provides methods for processing file system strings in a cross-platform manner.
  16. // Most of the methods don't do a complete parsing (such as examining a UNC hostname),
  17. // but they will handle most string operations.
  18. public static partial class Path
  19. {
  20. // Public static readonly variant of the separators. The Path implementation itself is using
  21. // internal const variant of the separators for better performance.
  22. public static readonly char DirectorySeparatorChar = PathInternal.DirectorySeparatorChar;
  23. public static readonly char AltDirectorySeparatorChar = PathInternal.AltDirectorySeparatorChar;
  24. public static readonly char VolumeSeparatorChar = PathInternal.VolumeSeparatorChar;
  25. public static readonly char PathSeparator = PathInternal.PathSeparator;
  26. // For generating random file names
  27. // 8 random bytes provides 12 chars in our encoding for the 8.3 name.
  28. private const int KeyLength = 8;
  29. [Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")]
  30. public static readonly char[] InvalidPathChars = GetInvalidPathChars();
  31. // Changes the extension of a file path. The path parameter
  32. // specifies a file path, and the extension parameter
  33. // specifies a file extension (with a leading period, such as
  34. // ".exe" or ".cs").
  35. //
  36. // The function returns a file path with the same root, directory, and base
  37. // name parts as path, but with the file extension changed to
  38. // the specified extension. If path is null, the function
  39. // returns null. If path does not contain a file extension,
  40. // the new file extension is appended to the path. If extension
  41. // is null, any existing extension is removed from path.
  42. public static string ChangeExtension(string path, string extension)
  43. {
  44. if (path != null)
  45. {
  46. string s = path;
  47. for (int i = path.Length - 1; i >= 0; i--)
  48. {
  49. char ch = path[i];
  50. if (ch == '.')
  51. {
  52. s = path.Substring(0, i);
  53. break;
  54. }
  55. if (PathInternal.IsDirectorySeparator(ch)) break;
  56. }
  57. if (extension != null && path.Length != 0)
  58. {
  59. s = (extension.Length == 0 || extension[0] != '.') ?
  60. s + "." + extension :
  61. s + extension;
  62. }
  63. return s;
  64. }
  65. return null;
  66. }
  67. /// <summary>
  68. /// Returns the directory portion of a file path. This method effectively
  69. /// removes the last segment of the given file path, i.e. it returns a
  70. /// string consisting of all characters up to but not including the last
  71. /// backslash ("\") in the file path. The returned value is null if the
  72. /// specified path is null, empty, or a root (such as "\", "C:", or
  73. /// "\\server\share").
  74. /// </summary>
  75. /// <remarks>
  76. /// Directory separators are normalized in the returned string.
  77. /// </remarks>
  78. public static string GetDirectoryName(string path)
  79. {
  80. if (path == null || PathInternal.IsEffectivelyEmpty(path.AsSpan()))
  81. return null;
  82. int end = GetDirectoryNameOffset(path.AsSpan());
  83. return end >= 0 ? PathInternal.NormalizeDirectorySeparators(path.Substring(0, end)) : null;
  84. }
  85. /// <summary>
  86. /// Returns the directory portion of a file path. The returned value is empty
  87. /// if the specified path is null, empty, or a root (such as "\", "C:", or
  88. /// "\\server\share").
  89. /// </summary>
  90. /// <remarks>
  91. /// Unlike the string overload, this method will not normalize directory separators.
  92. /// </remarks>
  93. public static ReadOnlySpan<char> GetDirectoryName(ReadOnlySpan<char> path)
  94. {
  95. if (PathInternal.IsEffectivelyEmpty(path))
  96. return ReadOnlySpan<char>.Empty;
  97. int end = GetDirectoryNameOffset(path);
  98. return end >= 0 ? path.Slice(0, end) : ReadOnlySpan<char>.Empty;
  99. }
  100. private static int GetDirectoryNameOffset(ReadOnlySpan<char> path)
  101. {
  102. int rootLength = PathInternal.GetRootLength(path);
  103. int end = path.Length;
  104. if (end <= rootLength)
  105. return -1;
  106. while (end > rootLength && !PathInternal.IsDirectorySeparator(path[--end]));
  107. // Trim off any remaining separators (to deal with C:\foo\\bar)
  108. while (end > rootLength && PathInternal.IsDirectorySeparator(path[end - 1]))
  109. end--;
  110. return end;
  111. }
  112. /// <summary>
  113. /// Returns the extension of the given path. The returned value includes the period (".") character of the
  114. /// extension except when you have a terminal period when you get string.Empty, such as ".exe" or ".cpp".
  115. /// The returned value is null if the given path is null or empty if the given path does not include an
  116. /// extension.
  117. /// </summary>
  118. public static string GetExtension(string path)
  119. {
  120. if (path == null)
  121. return null;
  122. return GetExtension(path.AsSpan()).ToString();
  123. }
  124. /// <summary>
  125. /// Returns the extension of the given path.
  126. /// </summary>
  127. /// <remarks>
  128. /// The returned value is an empty ReadOnlySpan if the given path does not include an extension.
  129. /// </remarks>
  130. public static ReadOnlySpan<char> GetExtension(ReadOnlySpan<char> path)
  131. {
  132. int length = path.Length;
  133. for (int i = length - 1; i >= 0; i--)
  134. {
  135. char ch = path[i];
  136. if (ch == '.')
  137. {
  138. if (i != length - 1)
  139. return path.Slice(i, length - i);
  140. else
  141. return ReadOnlySpan<char>.Empty;
  142. }
  143. if (PathInternal.IsDirectorySeparator(ch))
  144. break;
  145. }
  146. return ReadOnlySpan<char>.Empty;
  147. }
  148. /// <summary>
  149. /// Returns the name and extension parts of the given path. The resulting string contains
  150. /// the characters of path that follow the last separator in path. The resulting string is
  151. /// null if path is null.
  152. /// </summary>
  153. public static string GetFileName(string path)
  154. {
  155. if (path == null)
  156. return null;
  157. ReadOnlySpan<char> result = GetFileName(path.AsSpan());
  158. if (path.Length == result.Length)
  159. return path;
  160. return result.ToString();
  161. }
  162. /// <summary>
  163. /// The returned ReadOnlySpan contains the characters of the path that follows the last separator in path.
  164. /// </summary>
  165. public static ReadOnlySpan<char> GetFileName(ReadOnlySpan<char> path)
  166. {
  167. int root = GetPathRoot(path).Length;
  168. // We don't want to cut off "C:\file.txt:stream" (i.e. should be "file.txt:stream")
  169. // but we *do* want "C:Foo" => "Foo". This necessitates checking for the root.
  170. for (int i = path.Length; --i >= 0;)
  171. {
  172. if (i < root || PathInternal.IsDirectorySeparator(path[i]))
  173. return path.Slice(i + 1, path.Length - i - 1);
  174. }
  175. return path;
  176. }
  177. public static string GetFileNameWithoutExtension(string path)
  178. {
  179. if (path == null)
  180. return null;
  181. ReadOnlySpan<char> result = GetFileNameWithoutExtension(path.AsSpan());
  182. if (path.Length == result.Length)
  183. return path;
  184. return result.ToString();
  185. }
  186. /// <summary>
  187. /// Returns the characters between the last separator and last (.) in the path.
  188. /// </summary>
  189. public static ReadOnlySpan<char> GetFileNameWithoutExtension(ReadOnlySpan<char> path)
  190. {
  191. ReadOnlySpan<char> fileName = GetFileName(path);
  192. int lastPeriod = fileName.LastIndexOf('.');
  193. return lastPeriod == -1 ?
  194. fileName : // No extension was found
  195. fileName.Slice(0, lastPeriod);
  196. }
  197. /// <summary>
  198. /// Returns a cryptographically strong random 8.3 string that can be
  199. /// used as either a folder name or a file name.
  200. /// </summary>
  201. public static unsafe string GetRandomFileName()
  202. {
  203. byte* pKey = stackalloc byte[KeyLength];
  204. Interop.GetRandomBytes(pKey, KeyLength);
  205. #if MS_IO_REDIST
  206. return StringExtensions.Create(
  207. #else
  208. return string.Create(
  209. #endif
  210. 12, (IntPtr)pKey, (span, key) => // 12 == 8 + 1 (for period) + 3
  211. Populate83FileNameFromRandomBytes((byte*)key, KeyLength, span));
  212. }
  213. /// <summary>
  214. /// Returns true if the path is fixed to a specific drive or UNC path. This method does no
  215. /// validation of the path (URIs will be returned as relative as a result).
  216. /// Returns false if the path specified is relative to the current drive or working directory.
  217. /// </summary>
  218. /// <remarks>
  219. /// Handles paths that use the alternate directory separator. It is a frequent mistake to
  220. /// assume that rooted paths <see cref="Path.IsPathRooted(string)"/> are not relative. This isn't the case.
  221. /// "C:a" is drive relative- meaning that it will be resolved against the current directory
  222. /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory
  223. /// will not be used to modify the path).
  224. /// </remarks>
  225. /// <exception cref="ArgumentNullException">
  226. /// Thrown if <paramref name="path"/> is null.
  227. /// </exception>
  228. public static bool IsPathFullyQualified(string path)
  229. {
  230. if (path == null)
  231. throw new ArgumentNullException(nameof(path));
  232. return IsPathFullyQualified(path.AsSpan());
  233. }
  234. public static bool IsPathFullyQualified(ReadOnlySpan<char> path)
  235. {
  236. return !PathInternal.IsPartiallyQualified(path);
  237. }
  238. /// <summary>
  239. /// Tests if a path's file name includes a file extension. A trailing period
  240. /// is not considered an extension.
  241. /// </summary>
  242. public static bool HasExtension(string path)
  243. {
  244. if (path != null)
  245. {
  246. return HasExtension(path.AsSpan());
  247. }
  248. return false;
  249. }
  250. public static bool HasExtension(ReadOnlySpan<char> path)
  251. {
  252. for (int i = path.Length - 1; i >= 0; i--)
  253. {
  254. char ch = path[i];
  255. if (ch == '.')
  256. {
  257. return i != path.Length - 1;
  258. }
  259. if (PathInternal.IsDirectorySeparator(ch))
  260. break;
  261. }
  262. return false;
  263. }
  264. public static string Combine(string path1, string path2)
  265. {
  266. if (path1 == null || path2 == null)
  267. throw new ArgumentNullException((path1 == null) ? nameof(path1) : nameof(path2));
  268. return CombineInternal(path1, path2);
  269. }
  270. public static string Combine(string path1, string path2, string path3)
  271. {
  272. if (path1 == null || path2 == null || path3 == null)
  273. throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : nameof(path3));
  274. return CombineInternal(path1, path2, path3);
  275. }
  276. public static string Combine(string path1, string path2, string path3, string path4)
  277. {
  278. if (path1 == null || path2 == null || path3 == null || path4 == null)
  279. throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : (path3 == null) ? nameof(path3) : nameof(path4));
  280. return CombineInternal(path1, path2, path3, path4);
  281. }
  282. public static string Combine(params string[] paths)
  283. {
  284. if (paths == null)
  285. {
  286. throw new ArgumentNullException(nameof(paths));
  287. }
  288. int finalSize = 0;
  289. int firstComponent = 0;
  290. // We have two passes, the first calculates how large a buffer to allocate and does some precondition
  291. // checks on the paths passed in. The second actually does the combination.
  292. for (int i = 0; i < paths.Length; i++)
  293. {
  294. if (paths[i] == null)
  295. {
  296. throw new ArgumentNullException(nameof(paths));
  297. }
  298. if (paths[i].Length == 0)
  299. {
  300. continue;
  301. }
  302. if (IsPathRooted(paths[i]))
  303. {
  304. firstComponent = i;
  305. finalSize = paths[i].Length;
  306. }
  307. else
  308. {
  309. finalSize += paths[i].Length;
  310. }
  311. char ch = paths[i][paths[i].Length - 1];
  312. if (!PathInternal.IsDirectorySeparator(ch))
  313. finalSize++;
  314. }
  315. StringBuilder finalPath = StringBuilderCache.Acquire(finalSize);
  316. for (int i = firstComponent; i < paths.Length; i++)
  317. {
  318. if (paths[i].Length == 0)
  319. {
  320. continue;
  321. }
  322. if (finalPath.Length == 0)
  323. {
  324. finalPath.Append(paths[i]);
  325. }
  326. else
  327. {
  328. char ch = finalPath[finalPath.Length - 1];
  329. if (!PathInternal.IsDirectorySeparator(ch))
  330. {
  331. finalPath.Append(PathInternal.DirectorySeparatorChar);
  332. }
  333. finalPath.Append(paths[i]);
  334. }
  335. }
  336. return StringBuilderCache.GetStringAndRelease(finalPath);
  337. }
  338. // Unlike Combine(), Join() methods do not consider rooting. They simply combine paths, ensuring that there
  339. // is a directory separator between them.
  340. public static string Join(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2)
  341. {
  342. if (path1.Length == 0)
  343. return path2.ToString();
  344. if (path2.Length == 0)
  345. return path1.ToString();
  346. return JoinInternal(path1, path2);
  347. }
  348. public static string Join(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, ReadOnlySpan<char> path3)
  349. {
  350. if (path1.Length == 0)
  351. return Join(path2, path3);
  352. if (path2.Length == 0)
  353. return Join(path1, path3);
  354. if (path3.Length == 0)
  355. return Join(path1, path2);
  356. return JoinInternal(path1, path2, path3);
  357. }
  358. public static string Join(string path1, string path2)
  359. {
  360. return Join(path1.AsSpan(), path2.AsSpan());
  361. }
  362. public static string Join(string path1, string path2, string path3)
  363. {
  364. return Join(path1.AsSpan(), path2.AsSpan(), path3.AsSpan());
  365. }
  366. public static bool TryJoin(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, Span<char> destination, out int charsWritten)
  367. {
  368. charsWritten = 0;
  369. if (path1.Length == 0 && path2.Length == 0)
  370. return true;
  371. if (path1.Length == 0 || path2.Length == 0)
  372. {
  373. ref ReadOnlySpan<char> pathToUse = ref path1.Length == 0 ? ref path2 : ref path1;
  374. if (destination.Length < pathToUse.Length)
  375. {
  376. return false;
  377. }
  378. pathToUse.CopyTo(destination);
  379. charsWritten = pathToUse.Length;
  380. return true;
  381. }
  382. bool needsSeparator = !(PathInternal.EndsInDirectorySeparator(path1) || PathInternal.StartsWithDirectorySeparator(path2));
  383. int charsNeeded = path1.Length + path2.Length + (needsSeparator ? 1 : 0);
  384. if (destination.Length < charsNeeded)
  385. return false;
  386. path1.CopyTo(destination);
  387. if (needsSeparator)
  388. destination[path1.Length] = DirectorySeparatorChar;
  389. path2.CopyTo(destination.Slice(path1.Length + (needsSeparator ? 1 : 0)));
  390. charsWritten = charsNeeded;
  391. return true;
  392. }
  393. public static bool TryJoin(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, ReadOnlySpan<char> path3, Span<char> destination, out int charsWritten)
  394. {
  395. charsWritten = 0;
  396. if (path1.Length == 0 && path2.Length == 0 && path3.Length == 0)
  397. return true;
  398. if (path1.Length == 0)
  399. return TryJoin(path2, path3, destination, out charsWritten);
  400. if (path2.Length == 0)
  401. return TryJoin(path1, path3, destination, out charsWritten);
  402. if (path3.Length == 0)
  403. return TryJoin(path1, path2, destination, out charsWritten);
  404. int neededSeparators = PathInternal.EndsInDirectorySeparator(path1) || PathInternal.StartsWithDirectorySeparator(path2) ? 0 : 1;
  405. bool needsSecondSeparator = !(PathInternal.EndsInDirectorySeparator(path2) || PathInternal.StartsWithDirectorySeparator(path3));
  406. if (needsSecondSeparator)
  407. neededSeparators++;
  408. int charsNeeded = path1.Length + path2.Length + path3.Length + neededSeparators;
  409. if (destination.Length < charsNeeded)
  410. return false;
  411. bool result = TryJoin(path1, path2, destination, out charsWritten);
  412. Debug.Assert(result, "should never fail joining first two paths");
  413. if (needsSecondSeparator)
  414. destination[charsWritten++] = DirectorySeparatorChar;
  415. path3.CopyTo(destination.Slice(charsWritten));
  416. charsWritten += path3.Length;
  417. return true;
  418. }
  419. private static string CombineInternal(string first, string second)
  420. {
  421. if (string.IsNullOrEmpty(first))
  422. return second;
  423. if (string.IsNullOrEmpty(second))
  424. return first;
  425. if (IsPathRooted(second.AsSpan()))
  426. return second;
  427. return JoinInternal(first.AsSpan(), second.AsSpan());
  428. }
  429. private static string CombineInternal(string first, string second, string third)
  430. {
  431. if (string.IsNullOrEmpty(first))
  432. return CombineInternal(second, third);
  433. if (string.IsNullOrEmpty(second))
  434. return CombineInternal(first, third);
  435. if (string.IsNullOrEmpty(third))
  436. return CombineInternal(first, second);
  437. if (IsPathRooted(third.AsSpan()))
  438. return third;
  439. if (IsPathRooted(second.AsSpan()))
  440. return CombineInternal(second, third);
  441. return JoinInternal(first.AsSpan(), second.AsSpan(), third.AsSpan());
  442. }
  443. private static string CombineInternal(string first, string second, string third, string fourth)
  444. {
  445. if (string.IsNullOrEmpty(first))
  446. return CombineInternal(second, third, fourth);
  447. if (string.IsNullOrEmpty(second))
  448. return CombineInternal(first, third, fourth);
  449. if (string.IsNullOrEmpty(third))
  450. return CombineInternal(first, second, fourth);
  451. if (string.IsNullOrEmpty(fourth))
  452. return CombineInternal(first, second, third);
  453. if (IsPathRooted(fourth.AsSpan()))
  454. return fourth;
  455. if (IsPathRooted(third.AsSpan()))
  456. return CombineInternal(third, fourth);
  457. if (IsPathRooted(second.AsSpan()))
  458. return CombineInternal(second, third, fourth);
  459. return JoinInternal(first.AsSpan(), second.AsSpan(), third.AsSpan(), fourth.AsSpan());
  460. }
  461. private static unsafe string JoinInternal(ReadOnlySpan<char> first, ReadOnlySpan<char> second)
  462. {
  463. Debug.Assert(first.Length > 0 && second.Length > 0, "should have dealt with empty paths");
  464. bool hasSeparator = PathInternal.IsDirectorySeparator(first[first.Length - 1])
  465. || PathInternal.IsDirectorySeparator(second[0]);
  466. fixed (char* f = &MemoryMarshal.GetReference(first), s = &MemoryMarshal.GetReference(second))
  467. {
  468. #if MS_IO_REDIST
  469. return StringExtensions.Create(
  470. #else
  471. return string.Create(
  472. #endif
  473. first.Length + second.Length + (hasSeparator ? 0 : 1),
  474. (First: (IntPtr)f, FirstLength: first.Length, Second: (IntPtr)s, SecondLength: second.Length, HasSeparator: hasSeparator),
  475. (destination, state) =>
  476. {
  477. new Span<char>((char*)state.First, state.FirstLength).CopyTo(destination);
  478. if (!state.HasSeparator)
  479. destination[state.FirstLength] = PathInternal.DirectorySeparatorChar;
  480. new Span<char>((char*)state.Second, state.SecondLength).CopyTo(destination.Slice(state.FirstLength + (state.HasSeparator ? 0 : 1)));
  481. });
  482. }
  483. }
  484. private static unsafe string JoinInternal(ReadOnlySpan<char> first, ReadOnlySpan<char> second, ReadOnlySpan<char> third)
  485. {
  486. Debug.Assert(first.Length > 0 && second.Length > 0 && third.Length > 0, "should have dealt with empty paths");
  487. bool firstHasSeparator = PathInternal.IsDirectorySeparator(first[first.Length - 1])
  488. || PathInternal.IsDirectorySeparator(second[0]);
  489. bool thirdHasSeparator = PathInternal.IsDirectorySeparator(second[second.Length - 1])
  490. || PathInternal.IsDirectorySeparator(third[0]);
  491. fixed (char* f = &MemoryMarshal.GetReference(first), s = &MemoryMarshal.GetReference(second), t = &MemoryMarshal.GetReference(third))
  492. {
  493. #if MS_IO_REDIST
  494. return StringExtensions.Create(
  495. #else
  496. return string.Create(
  497. #endif
  498. first.Length + second.Length + third.Length + (firstHasSeparator ? 0 : 1) + (thirdHasSeparator ? 0 : 1),
  499. (First: (IntPtr)f, FirstLength: first.Length, Second: (IntPtr)s, SecondLength: second.Length,
  500. Third: (IntPtr)t, ThirdLength: third.Length, FirstHasSeparator: firstHasSeparator, ThirdHasSeparator: thirdHasSeparator),
  501. (destination, state) =>
  502. {
  503. new Span<char>((char*)state.First, state.FirstLength).CopyTo(destination);
  504. if (!state.FirstHasSeparator)
  505. destination[state.FirstLength] = PathInternal.DirectorySeparatorChar;
  506. new Span<char>((char*)state.Second, state.SecondLength).CopyTo(destination.Slice(state.FirstLength + (state.FirstHasSeparator ? 0 : 1)));
  507. if (!state.ThirdHasSeparator)
  508. destination[destination.Length - state.ThirdLength - 1] = PathInternal.DirectorySeparatorChar;
  509. new Span<char>((char*)state.Third, state.ThirdLength).CopyTo(destination.Slice(destination.Length - state.ThirdLength));
  510. });
  511. }
  512. }
  513. private static unsafe string JoinInternal(ReadOnlySpan<char> first, ReadOnlySpan<char> second, ReadOnlySpan<char> third, ReadOnlySpan<char> fourth)
  514. {
  515. Debug.Assert(first.Length > 0 && second.Length > 0 && third.Length > 0 && fourth.Length > 0, "should have dealt with empty paths");
  516. bool firstHasSeparator = PathInternal.IsDirectorySeparator(first[first.Length - 1])
  517. || PathInternal.IsDirectorySeparator(second[0]);
  518. bool thirdHasSeparator = PathInternal.IsDirectorySeparator(second[second.Length - 1])
  519. || PathInternal.IsDirectorySeparator(third[0]);
  520. bool fourthHasSeparator = PathInternal.IsDirectorySeparator(third[third.Length - 1])
  521. || PathInternal.IsDirectorySeparator(fourth[0]);
  522. fixed (char* f = &MemoryMarshal.GetReference(first), s = &MemoryMarshal.GetReference(second), t = &MemoryMarshal.GetReference(third), u = &MemoryMarshal.GetReference(fourth))
  523. {
  524. #if MS_IO_REDIST
  525. return StringExtensions.Create(
  526. #else
  527. return string.Create(
  528. #endif
  529. first.Length + second.Length + third.Length + fourth.Length + (firstHasSeparator ? 0 : 1) + (thirdHasSeparator ? 0 : 1) + (fourthHasSeparator ? 0 : 1),
  530. (First: (IntPtr)f, FirstLength: first.Length, Second: (IntPtr)s, SecondLength: second.Length,
  531. Third: (IntPtr)t, ThirdLength: third.Length, Fourth: (IntPtr)u, FourthLength:fourth.Length,
  532. FirstHasSeparator: firstHasSeparator, ThirdHasSeparator: thirdHasSeparator, FourthHasSeparator: fourthHasSeparator),
  533. (destination, state) =>
  534. {
  535. new Span<char>((char*)state.First, state.FirstLength).CopyTo(destination);
  536. if (!state.FirstHasSeparator)
  537. destination[state.FirstLength] = PathInternal.DirectorySeparatorChar;
  538. new Span<char>((char*)state.Second, state.SecondLength).CopyTo(destination.Slice(state.FirstLength + (state.FirstHasSeparator ? 0 : 1)));
  539. if (!state.ThirdHasSeparator)
  540. destination[state.FirstLength + state.SecondLength + (state.FirstHasSeparator ? 0 : 1)] = PathInternal.DirectorySeparatorChar;
  541. new Span<char>((char*)state.Third, state.ThirdLength).CopyTo(destination.Slice(state.FirstLength + state.SecondLength + (state.FirstHasSeparator ? 0 : 1) + (state.ThirdHasSeparator ? 0 : 1)));
  542. if (!state.FourthHasSeparator)
  543. destination[destination.Length - state.FourthLength - 1] = PathInternal.DirectorySeparatorChar;
  544. new Span<char>((char*)state.Fourth, state.FourthLength).CopyTo(destination.Slice(destination.Length - state.FourthLength));
  545. });
  546. }
  547. }
  548. private static ReadOnlySpan<byte> Base32Char => new byte[32] { // uses C# compiler's optimization for static byte[] data
  549. (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h',
  550. (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p',
  551. (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x',
  552. (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5'};
  553. private static unsafe void Populate83FileNameFromRandomBytes(byte* bytes, int byteCount, Span<char> chars)
  554. {
  555. // This method requires bytes of length 8 and chars of length 12.
  556. Debug.Assert(bytes != null);
  557. Debug.Assert(byteCount == 8, $"Unexpected {nameof(byteCount)}");
  558. Debug.Assert(chars.Length == 12, $"Unexpected {nameof(chars)}.Length");
  559. byte b0 = bytes[0];
  560. byte b1 = bytes[1];
  561. byte b2 = bytes[2];
  562. byte b3 = bytes[3];
  563. byte b4 = bytes[4];
  564. // Consume the 5 Least significant bits of the first 5 bytes
  565. chars[0] = (char)Base32Char[b0 & 0x1F];
  566. chars[1] = (char)Base32Char[b1 & 0x1F];
  567. chars[2] = (char)Base32Char[b2 & 0x1F];
  568. chars[3] = (char)Base32Char[b3 & 0x1F];
  569. chars[4] = (char)Base32Char[b4 & 0x1F];
  570. // Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4
  571. chars[5] = (char)Base32Char[
  572. ((b0 & 0xE0) >> 5) |
  573. ((b3 & 0x60) >> 2)];
  574. chars[6] = (char)Base32Char[
  575. ((b1 & 0xE0) >> 5) |
  576. ((b4 & 0x60) >> 2)];
  577. // Consume 3 MSB bits of b2, 1 MSB bit of b3, b4
  578. b2 >>= 5;
  579. Debug.Assert(((b2 & 0xF8) == 0), "Unexpected set bits");
  580. if ((b3 & 0x80) != 0)
  581. b2 |= 0x08;
  582. if ((b4 & 0x80) != 0)
  583. b2 |= 0x10;
  584. chars[7] = (char)Base32Char[b2];
  585. // Set the file extension separator
  586. chars[8] = '.';
  587. // Consume the 5 Least significant bits of the remaining 3 bytes
  588. chars[9] = (char)Base32Char[bytes[5] & 0x1F];
  589. chars[10] = (char)Base32Char[bytes[6] & 0x1F];
  590. chars[11] = (char)Base32Char[bytes[7] & 0x1F];
  591. }
  592. /// <summary>
  593. /// Create a relative path from one path to another. Paths will be resolved before calculating the difference.
  594. /// Default path comparison for the active platform will be used (OrdinalIgnoreCase for Windows or Mac, Ordinal for Unix).
  595. /// </summary>
  596. /// <param name="relativeTo">The source path the output should be relative to. This path is always considered to be a directory.</param>
  597. /// <param name="path">The destination path.</param>
  598. /// <returns>The relative path or <paramref name="path"/> if the paths don't share the same root.</returns>
  599. /// <exception cref="ArgumentNullException">Thrown if <paramref name="relativeTo"/> or <paramref name="path"/> is <c>null</c> or an empty string.</exception>
  600. public static string GetRelativePath(string relativeTo, string path)
  601. {
  602. return GetRelativePath(relativeTo, path, StringComparison);
  603. }
  604. private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType)
  605. {
  606. if (string.IsNullOrEmpty(relativeTo)) throw new ArgumentNullException(nameof(relativeTo));
  607. if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentNullException(nameof(path));
  608. Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase);
  609. relativeTo = GetFullPath(relativeTo);
  610. path = GetFullPath(path);
  611. // Need to check if the roots are different- if they are we need to return the "to" path.
  612. if (!PathInternal.AreRootsEqual(relativeTo, path, comparisonType))
  613. return path;
  614. int commonLength = PathInternal.GetCommonPathLength(relativeTo, path, ignoreCase: comparisonType == StringComparison.OrdinalIgnoreCase);
  615. // If there is nothing in common they can't share the same root, return the "to" path as is.
  616. if (commonLength == 0)
  617. return path;
  618. // Trailing separators aren't significant for comparison
  619. int relativeToLength = relativeTo.Length;
  620. if (PathInternal.EndsInDirectorySeparator(relativeTo.AsSpan()))
  621. relativeToLength--;
  622. bool pathEndsInSeparator = PathInternal.EndsInDirectorySeparator(path.AsSpan());
  623. int pathLength = path.Length;
  624. if (pathEndsInSeparator)
  625. pathLength--;
  626. // If we have effectively the same path, return "."
  627. if (relativeToLength == pathLength && commonLength >= relativeToLength) return ".";
  628. // We have the same root, we need to calculate the difference now using the
  629. // common Length and Segment count past the length.
  630. //
  631. // Some examples:
  632. //
  633. // C:\Foo C:\Bar L3, S1 -> ..\Bar
  634. // C:\Foo C:\Foo\Bar L6, S0 -> Bar
  635. // C:\Foo\Bar C:\Bar\Bar L3, S2 -> ..\..\Bar\Bar
  636. // C:\Foo\Foo C:\Foo\Bar L7, S1 -> ..\Bar
  637. StringBuilder sb = StringBuilderCache.Acquire(Math.Max(relativeTo.Length, path.Length));
  638. // Add parent segments for segments past the common on the "from" path
  639. if (commonLength < relativeToLength)
  640. {
  641. sb.Append("..");
  642. for (int i = commonLength + 1; i < relativeToLength; i++)
  643. {
  644. if (PathInternal.IsDirectorySeparator(relativeTo[i]))
  645. {
  646. sb.Append(DirectorySeparatorChar);
  647. sb.Append("..");
  648. }
  649. }
  650. }
  651. else if (PathInternal.IsDirectorySeparator(path[commonLength]))
  652. {
  653. // No parent segments and we need to eat the initial separator
  654. // (C:\Foo C:\Foo\Bar case)
  655. commonLength++;
  656. }
  657. // Now add the rest of the "to" path, adding back the trailing separator
  658. int differenceLength = pathLength - commonLength;
  659. if (pathEndsInSeparator)
  660. differenceLength++;
  661. if (differenceLength > 0)
  662. {
  663. if (sb.Length > 0)
  664. {
  665. sb.Append(DirectorySeparatorChar);
  666. }
  667. sb.Append(path, commonLength, differenceLength);
  668. }
  669. return StringBuilderCache.GetStringAndRelease(sb);
  670. }
  671. /// <summary>Returns a comparison that can be used to compare file and directory names for equality.</summary>
  672. internal static StringComparison StringComparison
  673. {
  674. get
  675. {
  676. return IsCaseSensitive ?
  677. StringComparison.Ordinal :
  678. StringComparison.OrdinalIgnoreCase;
  679. }
  680. }
  681. }
  682. }