Path.Windows.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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.Text;
  6. #if MS_IO_REDIST
  7. using System;
  8. using System.IO;
  9. namespace Microsoft.IO
  10. #else
  11. namespace System.IO
  12. #endif
  13. {
  14. public static partial class Path
  15. {
  16. public static char[] GetInvalidFileNameChars() => new char[]
  17. {
  18. '\"', '<', '>', '|', '\0',
  19. (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
  20. (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
  21. (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
  22. (char)31, ':', '*', '?', '\\', '/'
  23. };
  24. public static char[] GetInvalidPathChars() => new char[]
  25. {
  26. '|', '\0',
  27. (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
  28. (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
  29. (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
  30. (char)31
  31. };
  32. // Expands the given path to a fully qualified path.
  33. public static string GetFullPath(string path)
  34. {
  35. if (path == null)
  36. throw new ArgumentNullException(nameof(path));
  37. // If the path would normalize to string empty, we'll consider it empty
  38. if (PathInternal.IsEffectivelyEmpty(path.AsSpan()))
  39. throw new ArgumentException(SR.Arg_PathEmpty, nameof(path));
  40. // Embedded null characters are the only invalid character case we trully care about.
  41. // This is because the nulls will signal the end of the string to Win32 and therefore have
  42. // unpredictable results.
  43. if (path.Contains('\0'))
  44. throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path));
  45. if (PathInternal.IsExtended(path.AsSpan()))
  46. {
  47. // \\?\ paths are considered normalized by definition. Windows doesn't normalize \\?\
  48. // paths and neither should we. Even if we wanted to GetFullPathName does not work
  49. // properly with device paths. If one wants to pass a \\?\ path through normalization
  50. // one can chop off the prefix, pass it to GetFullPath and add it again.
  51. return path;
  52. }
  53. return PathHelper.Normalize(path);
  54. }
  55. public static string GetFullPath(string path, string basePath)
  56. {
  57. if (path == null)
  58. throw new ArgumentNullException(nameof(path));
  59. if (basePath == null)
  60. throw new ArgumentNullException(nameof(basePath));
  61. if (!IsPathFullyQualified(basePath))
  62. throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath));
  63. if (basePath.Contains('\0') || path.Contains('\0'))
  64. throw new ArgumentException(SR.Argument_InvalidPathChars);
  65. if (IsPathFullyQualified(path))
  66. return GetFullPath(path);
  67. if (PathInternal.IsEffectivelyEmpty(path.AsSpan()))
  68. return basePath;
  69. int length = path.Length;
  70. string combinedPath = null;
  71. if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])))
  72. {
  73. // Path is current drive rooted i.e. starts with \:
  74. // "\Foo" and "C:\Bar" => "C:\Foo"
  75. // "\Foo" and "\\?\C:\Bar" => "\\?\C:\Foo"
  76. combinedPath = Join(GetPathRoot(basePath.AsSpan()), path.AsSpan(1)); // Cut the separator to ensure we don't end up with two separators when joining with the root.
  77. }
  78. else if (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar)
  79. {
  80. // Drive relative paths
  81. Debug.Assert(length == 2 || !PathInternal.IsDirectorySeparator(path[2]));
  82. if (GetVolumeName(path.AsSpan()).EqualsOrdinal(GetVolumeName(basePath.AsSpan())))
  83. {
  84. // Matching root
  85. // "C:Foo" and "C:\Bar" => "C:\Bar\Foo"
  86. // "C:Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo"
  87. combinedPath = Join(basePath.AsSpan(), path.AsSpan(2));
  88. }
  89. else
  90. {
  91. // No matching root, root to specified drive
  92. // "D:Foo" and "C:\Bar" => "D:Foo"
  93. // "D:Foo" and "\\?\C:\Bar" => "\\?\D:\Foo"
  94. combinedPath = !PathInternal.IsDevice(basePath.AsSpan())
  95. ? path.Insert(2, @"\")
  96. : length == 2
  97. ? JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(), @"\".AsSpan())
  98. : JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(0, 2), @"\".AsSpan(), path.AsSpan(2));
  99. }
  100. }
  101. else
  102. {
  103. // "Simple" relative path
  104. // "Foo" and "C:\Bar" => "C:\Bar\Foo"
  105. // "Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo"
  106. combinedPath = JoinInternal(basePath.AsSpan(), path.AsSpan());
  107. }
  108. // Device paths are normalized by definition, so passing something of this format (i.e. \\?\C:\.\tmp, \\.\C:\foo)
  109. // to Windows APIs won't do anything by design. Additionally, GetFullPathName() in Windows doesn't root
  110. // them properly. As such we need to manually remove segments and not use GetFullPath().
  111. return PathInternal.IsDevice(combinedPath.AsSpan())
  112. ? PathInternal.RemoveRelativeSegments(combinedPath, PathInternal.GetRootLength(combinedPath.AsSpan()))
  113. : GetFullPath(combinedPath);
  114. }
  115. public static string GetTempPath()
  116. {
  117. Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
  118. var builder = new ValueStringBuilder(initialBuffer);
  119. GetTempPath(ref builder);
  120. string path = PathHelper.Normalize(ref builder);
  121. builder.Dispose();
  122. return path;
  123. }
  124. private static void GetTempPath(ref ValueStringBuilder builder)
  125. {
  126. uint result = 0;
  127. while ((result = Interop.Kernel32.GetTempPathW(builder.Capacity, ref builder.GetPinnableReference())) > builder.Capacity)
  128. {
  129. // Reported size is greater than the buffer size. Increase the capacity.
  130. builder.EnsureCapacity(checked((int)result));
  131. }
  132. if (result == 0)
  133. throw Win32Marshal.GetExceptionForLastWin32Error();
  134. builder.Length = (int)result;
  135. }
  136. // Returns a unique temporary file name, and creates a 0-byte file by that
  137. // name on disk.
  138. public static string GetTempFileName()
  139. {
  140. Span<char> initialTempPathBuffer = stackalloc char[PathInternal.MaxShortPath];
  141. ValueStringBuilder tempPathBuilder = new ValueStringBuilder(initialTempPathBuffer);
  142. GetTempPath(ref tempPathBuilder);
  143. Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath];
  144. var builder = new ValueStringBuilder(initialBuffer);
  145. uint result = Interop.Kernel32.GetTempFileNameW(
  146. ref tempPathBuilder.GetPinnableReference(), "tmp", 0, ref builder.GetPinnableReference());
  147. tempPathBuilder.Dispose();
  148. if (result == 0)
  149. throw Win32Marshal.GetExceptionForLastWin32Error();
  150. builder.Length = builder.RawChars.IndexOf('\0');
  151. string path = PathHelper.Normalize(ref builder);
  152. builder.Dispose();
  153. return path;
  154. }
  155. // Tests if the given path contains a root. A path is considered rooted
  156. // if it starts with a backslash ("\") or a valid drive letter and a colon (":").
  157. public static bool IsPathRooted(string path)
  158. {
  159. return path != null && IsPathRooted(path.AsSpan());
  160. }
  161. public static bool IsPathRooted(ReadOnlySpan<char> path)
  162. {
  163. int length = path.Length;
  164. return (length >= 1 && PathInternal.IsDirectorySeparator(path[0]))
  165. || (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar);
  166. }
  167. // Returns the root portion of the given path. The resulting string
  168. // consists of those rightmost characters of the path that constitute the
  169. // root of the path. Possible patterns for the resulting string are: An
  170. // empty string (a relative path on the current drive), "\" (an absolute
  171. // path on the current drive), "X:" (a relative path on a given drive,
  172. // where X is the drive letter), "X:\" (an absolute path on a given drive),
  173. // and "\\server\share" (a UNC path for a given server and share name).
  174. // The resulting string is null if path is null. If the path is empty or
  175. // only contains whitespace characters an ArgumentException gets thrown.
  176. public static string GetPathRoot(string path)
  177. {
  178. if (PathInternal.IsEffectivelyEmpty(path.AsSpan()))
  179. return null;
  180. ReadOnlySpan<char> result = GetPathRoot(path.AsSpan());
  181. if (path.Length == result.Length)
  182. return PathInternal.NormalizeDirectorySeparators(path);
  183. return PathInternal.NormalizeDirectorySeparators(result.ToString());
  184. }
  185. /// <remarks>
  186. /// Unlike the string overload, this method will not normalize directory separators.
  187. /// </remarks>
  188. public static ReadOnlySpan<char> GetPathRoot(ReadOnlySpan<char> path)
  189. {
  190. if (PathInternal.IsEffectivelyEmpty(path))
  191. return ReadOnlySpan<char>.Empty;
  192. int pathRoot = PathInternal.GetRootLength(path);
  193. return pathRoot <= 0 ? ReadOnlySpan<char>.Empty : path.Slice(0, pathRoot);
  194. }
  195. /// <summary>Gets whether the system is case-sensitive.</summary>
  196. internal static bool IsCaseSensitive { get { return false; } }
  197. /// <summary>
  198. /// Returns the volume name for dos, UNC and device paths.
  199. /// </summary>
  200. internal static ReadOnlySpan<char> GetVolumeName(ReadOnlySpan<char> path)
  201. {
  202. // 3 cases: UNC ("\\server\share"), Device ("\\?\C:\"), or Dos ("C:\")
  203. ReadOnlySpan<char> root = GetPathRoot(path);
  204. if (root.Length == 0)
  205. return root;
  206. int offset = GetUncRootLength(path);
  207. if (offset >= 0)
  208. {
  209. // Cut from "\\?\UNC\Server\Share" to "Server\Share"
  210. // Cut from "\\Server\Share" to "Server\Share"
  211. return TrimEndingDirectorySeparator(root.Slice(offset));
  212. }
  213. else if (PathInternal.IsDevice(path))
  214. {
  215. return TrimEndingDirectorySeparator(root.Slice(4)); // Cut from "\\?\C:\" to "C:"
  216. }
  217. return TrimEndingDirectorySeparator(root); // e.g. "C:"
  218. }
  219. /// <summary>
  220. /// Trims the ending directory separator if present.
  221. /// </summary>
  222. /// <param name="path"></param>
  223. internal static ReadOnlySpan<char> TrimEndingDirectorySeparator(ReadOnlySpan<char> path) =>
  224. PathInternal.EndsInDirectorySeparator(path) ?
  225. path.Slice(0, path.Length - 1) :
  226. path;
  227. /// <summary>
  228. /// Returns offset as -1 if the path is not in Unc format, otherwise returns the root length.
  229. /// </summary>
  230. /// <param name="path"></param>
  231. /// <returns></returns>
  232. internal static int GetUncRootLength(ReadOnlySpan<char> path)
  233. {
  234. bool isDevice = PathInternal.IsDevice(path);
  235. if (!isDevice && path.Slice(0, 2).EqualsOrdinal(@"\\".AsSpan()) )
  236. return 2;
  237. else if (isDevice && path.Length >= 8
  238. && (path.Slice(0, 8).EqualsOrdinal(PathInternal.UncExtendedPathPrefix.AsSpan())
  239. || path.Slice(5, 4).EqualsOrdinal(@"UNC\".AsSpan())))
  240. return 8;
  241. return -1;
  242. }
  243. }
  244. }