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.
5 using System.Diagnostics;
10 public static partial class Path
12 public static char[] GetInvalidFileNameChars() => new char[]
14 '\"', '<', '>', '|', '\0',
15 (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
16 (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
17 (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
18 (char)31, ':', '*', '?', '\\', '/'
21 public static char[] GetInvalidPathChars() => new char[]
24 (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
25 (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
26 (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
30 // Expands the given path to a fully qualified path.
31 public static string GetFullPath(string path)
34 throw new ArgumentNullException(nameof(path));
36 // If the path would normalize to string empty, we'll consider it empty
37 if (PathInternal.IsEffectivelyEmpty(path))
38 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.IndexOf('\0') != -1)
44 throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path));
46 if (PathInternal.IsExtended(path))
48 // \\?\ paths are considered normalized by definition. Windows doesn't normalize \\?\
49 // paths and neither should we. Even if we wanted to GetFullPathName does not work
50 // properly with device paths. If one wants to pass a \\?\ path through normalization
51 // one can chop off the prefix, pass it to GetFullPath and add it again.
55 return PathHelper.Normalize(path);
58 public static string GetFullPath(string path, string basePath)
61 throw new ArgumentNullException(nameof(path));
64 throw new ArgumentNullException(nameof(basePath));
66 if (!IsPathFullyQualified(basePath))
67 throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath));
69 if (basePath.Contains('\0') || path.Contains('\0'))
70 throw new ArgumentException(SR.Argument_InvalidPathChars);
72 if (IsPathFullyQualified(path))
73 return GetFullPath(path);
75 if (PathInternal.IsEffectivelyEmpty(path))
78 int length = path.Length;
79 string combinedPath = null;
81 if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])))
83 // Path is current drive rooted i.e. starts with \:
84 // "\Foo" and "C:\Bar" => "C:\Foo"
85 // "\Foo" and "\\?\C:\Bar" => "\\?\C:\Foo"
86 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.
88 else if (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar)
90 // Drive relative paths
91 Debug.Assert(length == 2 || !PathInternal.IsDirectorySeparator(path[2]));
93 if (GetVolumeName(path).EqualsOrdinal(GetVolumeName(basePath)))
96 // "C:Foo" and "C:\Bar" => "C:\Bar\Foo"
97 // "C:Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo"
98 combinedPath = Join(basePath, path.AsSpan(2));
102 // No matching root, root to specified drive
103 // "D:Foo" and "C:\Bar" => "D:Foo"
104 // "D:Foo" and "\\?\C:\Bar" => "\\?\D:\Foo"
105 combinedPath = !PathInternal.IsDevice(basePath)
106 ? path.Insert(2, @"\")
108 ? JoinInternal(basePath.AsSpan(0, 4), path, @"\")
109 : JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(0, 2), @"\", path.AsSpan(2));
114 // "Simple" relative path
115 // "Foo" and "C:\Bar" => "C:\Bar\Foo"
116 // "Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo"
117 combinedPath = JoinInternal(basePath, path);
120 // Device paths are normalized by definition, so passing something of this format
121 // to GetFullPath() won't do anything by design. Additionally, GetFullPathName() in
122 // Windows doesn't root them properly. As such we need to manually remove segments.
123 return PathInternal.IsDevice(combinedPath)
124 // Paths at this point are in the form of \\?\C:\.\tmp we skip to the last character of the root when calling RemoveRelativeSegments to remove relative paths in such cases.
125 ? PathInternal.RemoveRelativeSegments(combinedPath, PathInternal.GetRootLength(combinedPath) - 1)
126 : GetFullPath(combinedPath);
129 public static string GetTempPath()
131 StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH);
132 uint r = Interop.Kernel32.GetTempPathW(Interop.Kernel32.MAX_PATH, sb);
134 throw Win32Marshal.GetExceptionForLastWin32Error();
135 return GetFullPath(StringBuilderCache.GetStringAndRelease(sb));
138 // Returns a unique temporary file name, and creates a 0-byte file by that
140 public static string GetTempFileName()
142 string path = GetTempPath();
144 StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH);
145 uint r = Interop.Kernel32.GetTempFileNameW(path, "tmp", 0, sb);
147 throw Win32Marshal.GetExceptionForLastWin32Error();
148 return StringBuilderCache.GetStringAndRelease(sb);
151 // Tests if the given path contains a root. A path is considered rooted
152 // if it starts with a backslash ("\") or a valid drive letter and a colon (":").
153 public static bool IsPathRooted(string path)
155 return path != null && IsPathRooted(path.AsSpan());
158 public static bool IsPathRooted(ReadOnlySpan<char> path)
160 int length = path.Length;
161 return (length >= 1 && PathInternal.IsDirectorySeparator(path[0]))
162 || (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar);
165 // Returns the root portion of the given path. The resulting string
166 // consists of those rightmost characters of the path that constitute the
167 // root of the path. Possible patterns for the resulting string are: An
168 // empty string (a relative path on the current drive), "\" (an absolute
169 // path on the current drive), "X:" (a relative path on a given drive,
170 // where X is the drive letter), "X:\" (an absolute path on a given drive),
171 // and "\\server\share" (a UNC path for a given server and share name).
172 // The resulting string is null if path is null. If the path is empty or
173 // only contains whitespace characters an ArgumentException gets thrown.
174 public static string GetPathRoot(string path)
176 if (PathInternal.IsEffectivelyEmpty(path))
179 ReadOnlySpan<char> result = GetPathRoot(path.AsSpan());
180 if (path.Length == result.Length)
181 return PathInternal.NormalizeDirectorySeparators(path);
183 return PathInternal.NormalizeDirectorySeparators(new string(result));
187 /// Unlike the string overload, this method will not normalize directory separators.
189 public static ReadOnlySpan<char> GetPathRoot(ReadOnlySpan<char> path)
191 if (PathInternal.IsEffectivelyEmpty(path))
192 return ReadOnlySpan<char>.Empty;
194 int pathRoot = PathInternal.GetRootLength(path);
195 return pathRoot <= 0 ? ReadOnlySpan<char>.Empty : path.Slice(0, pathRoot);
198 /// <summary>Gets whether the system is case-sensitive.</summary>
199 internal static bool IsCaseSensitive { get { return false; } }
202 /// Returns the volume name for dos, UNC and device paths.
204 internal static ReadOnlySpan<char> GetVolumeName(ReadOnlySpan<char> path)
206 // 3 cases: UNC ("\\server\share"), Device ("\\?\C:\"), or Dos ("C:\")
207 ReadOnlySpan<char> root = GetPathRoot(path);
208 if (root.Length == 0)
211 int offset = GetUncRootLength(path);
214 // Cut from "\\?\UNC\Server\Share" to "Server\Share"
215 // Cut from "\\Server\Share" to "Server\Share"
216 return TrimEndingDirectorySeparator(root.Slice(offset));
218 else if (PathInternal.IsDevice(path))
220 return TrimEndingDirectorySeparator(root.Slice(4)); // Cut from "\\?\C:\" to "C:"
223 return TrimEndingDirectorySeparator(root); // e.g. "C:"
227 /// Trims the ending directory separator if present.
229 /// <param name="path"></param>
230 internal static ReadOnlySpan<char> TrimEndingDirectorySeparator(ReadOnlySpan<char> path) =>
231 PathInternal.EndsInDirectorySeparator(path) ?
232 path.Slice(0, path.Length - 1) :
236 /// Returns offset as -1 if the path is not in Unc format, otherwise returns the root length.
238 /// <param name="path"></param>
239 /// <returns></returns>
240 internal static int GetUncRootLength(ReadOnlySpan<char> path)
242 bool isDevice = PathInternal.IsDevice(path);
244 if (!isDevice && path.Slice(0, 2).EqualsOrdinal(@"\\") )
246 else if (isDevice && path.Length >= 8
247 && (path.Slice(0, 8).EqualsOrdinal(PathInternal.UncExtendedPathPrefix)
248 || path.Slice(5, 4).EqualsOrdinal(@"UNC\")))