2 // System.Web.VirtualPathUtility.cs
5 // Chris Toshok (toshok@ximian.com)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
10 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Web.Util;
36 namespace System.Web {
41 static class VirtualPathUtility
43 public static string AppendTrailingSlash (string virtualPath)
45 if (virtualPath == null)
48 int length = virtualPath.Length;
49 if (length == 0 || virtualPath [length - 1] == '/')
52 return virtualPath + "/";
55 public static string Combine (string basePath, string relativePath)
57 basePath = Normalize (basePath);
59 if (IsRooted (relativePath))
60 return Normalize (relativePath);
62 if (basePath [basePath.Length - 1] != '/') {
63 if (basePath.Length > 1) {
64 int lastSlash = basePath.LastIndexOf ('/');
66 basePath = basePath.Substring (0, lastSlash + 1);
73 return Normalize (basePath + relativePath);
76 public static string GetDirectory (string virtualPath)
78 return GetDirectory (virtualPath, true);
81 internal static string GetDirectory (string virtualPath, bool normalize)
84 virtualPath = Normalize (virtualPath);
86 if (IsAppRelative (virtualPath) && virtualPath.Length < 3) { // "~" or "~/"
87 virtualPath = ToAbsolute (virtualPath);
90 if (virtualPath.Length == 1 && virtualPath [0] == '/') { // "/"
94 int last = virtualPath.LastIndexOf ('/', virtualPath.Length - 2, virtualPath.Length - 2);
96 return virtualPath.Substring (0, last + 1);
101 public static string GetExtension (string virtualPath)
103 if (StrUtils.IsNullOrEmpty (virtualPath))
104 throw new ArgumentNullException ("virtualPath");
106 virtualPath = Canonize (virtualPath);
108 int dot = virtualPath.LastIndexOf ('.');
109 if (dot == -1 || dot == virtualPath.Length - 1 || dot < virtualPath.LastIndexOf ('/'))
112 return virtualPath.Substring (dot);
115 public static string GetFileName (string virtualPath)
117 virtualPath = Normalize (virtualPath);
119 if (IsAppRelative (virtualPath) && virtualPath.Length < 3) { // "~" or "~/"
120 virtualPath = ToAbsolute (virtualPath);
123 if (virtualPath.Length == 1 && virtualPath [0] == '/') { // "/"
127 virtualPath = RemoveTrailingSlash (virtualPath);
128 int last = virtualPath.LastIndexOf ('/');
129 return virtualPath.Substring (last + 1);
132 internal static bool IsRooted (string virtualPath)
134 return IsAbsolute (virtualPath) || IsAppRelative (virtualPath);
137 public static bool IsAbsolute (string virtualPath)
139 if (StrUtils.IsNullOrEmpty (virtualPath))
140 throw new ArgumentNullException ("virtualPath");
142 return (virtualPath [0] == '/' || virtualPath [0] == '\\');
145 public static bool IsAppRelative (string virtualPath)
147 if (StrUtils.IsNullOrEmpty (virtualPath))
148 throw new ArgumentNullException ("virtualPath");
150 if (virtualPath.Length == 1 && virtualPath [0] == '~')
153 if (virtualPath [0] == '~' && (virtualPath [1] == '/' || virtualPath [1] == '\\'))
159 // MSDN: If the fromPath and toPath parameters are not rooted; that is,
160 // they do not equal the root operator (the tilde [~]), do not start with a tilde (~),
161 // such as a tilde and a slash mark (~/) or a tilde and a double backslash (~//),
162 // or do not start with a slash mark (/), an ArgumentException exception is thrown.
163 public static string MakeRelative (string fromPath, string toPath)
165 if (fromPath == null || toPath == null)
166 throw new NullReferenceException (); // yeah!
171 toPath = ToAbsoluteInternal (toPath);
172 fromPath = ToAbsoluteInternal (fromPath);
174 if (String.CompareOrdinal (fromPath, toPath) == 0 && fromPath [fromPath.Length - 1] == '/')
177 string [] toPath_parts = toPath.Split ('/');
178 string [] fromPath_parts = fromPath.Split ('/');
180 while (toPath_parts [dest] == fromPath_parts [dest]) {
181 if (toPath_parts.Length == (dest + 1) || fromPath_parts.Length == (dest + 1)) {
186 StringBuilder res = new StringBuilder();
187 for (int i = 1; i < fromPath_parts.Length - dest; i++) {
190 for (int i = dest; i < toPath_parts.Length; i++) {
191 res.Append (toPath_parts [i]);
192 if (i < toPath_parts.Length - 1)
195 return res.ToString ();
198 static string ToAbsoluteInternal (string virtualPath)
200 if (IsAppRelative (virtualPath))
201 return ToAbsolute (virtualPath, HttpRuntime.AppDomainAppVirtualPath);
202 else if (IsAbsolute (virtualPath))
203 return Normalize (virtualPath);
205 throw new ArgumentOutOfRangeException ("Specified argument was out of the range of valid values.");
208 public static string RemoveTrailingSlash (string virtualPath)
210 if (virtualPath == null || virtualPath == "")
213 int last = virtualPath.Length - 1;
214 if (last == 0 || virtualPath [last] != '/')
217 return virtualPath.Substring (0, last);
220 public static string ToAbsolute (string virtualPath)
222 return ToAbsolute (virtualPath, true);
225 internal static string ToAbsolute (string virtualPath, bool normalize)
227 if (IsAbsolute (virtualPath)) {
229 return Normalize (virtualPath);
234 string apppath = HttpRuntime.AppDomainAppVirtualPath;
236 throw new HttpException ("The path to the application is not known");
238 if (virtualPath.Length == 1 && virtualPath [0] == '~')
241 return ToAbsolute (virtualPath,apppath);
244 // If virtualPath is:
245 // Absolute, the ToAbsolute method returns the virtual path with no changes.
246 // Application relative, the ToAbsolute method adds applicationPath to the beginning of the virtual path.
247 // Not rooted, the ToAbsolute method raises an ArgumentOutOfRangeException exception.
248 public static string ToAbsolute (string virtualPath, string applicationPath)
250 return ToAbsolute (virtualPath, applicationPath, true);
253 public static string ToAbsolute (string virtualPath, string applicationPath, bool normalize)
255 if (StrUtils.IsNullOrEmpty (applicationPath))
256 throw new ArgumentNullException ("applicationPath");
258 if (StrUtils.IsNullOrEmpty (virtualPath))
259 throw new ArgumentNullException ("virtualPath");
261 if (IsAppRelative(virtualPath)) {
262 if (applicationPath [0] != '/')
263 throw new ArgumentException ("appPath is not rooted", "applicationPath");
265 string path = applicationPath + (virtualPath.Length == 1 ? "/" : virtualPath.Substring (1));
267 return Normalize (path);
272 if (virtualPath [0] != '/')
273 throw new ArgumentException (String.Format ("Relative path not allowed: '{0}'", virtualPath));
276 return Normalize (virtualPath);
282 public static string ToAppRelative (string virtualPath)
284 string apppath = HttpRuntime.AppDomainAppVirtualPath;
286 throw new HttpException ("The path to the application is not known");
288 return ToAppRelative (virtualPath, apppath);
291 public static string ToAppRelative (string virtualPath, string applicationPath)
293 virtualPath = Normalize (virtualPath);
294 if (IsAppRelative (virtualPath))
297 if (!IsAbsolute (applicationPath))
298 throw new ArgumentException ("appPath is not absolute", "applicationPath");
300 applicationPath = Normalize (applicationPath);
302 if (applicationPath.Length == 1)
303 return "~" + virtualPath;
305 int appPath_lenght = applicationPath.Length;
306 if (String.CompareOrdinal (virtualPath, applicationPath) == 0)
308 if (String.CompareOrdinal (virtualPath, 0, applicationPath, 0, appPath_lenght) == 0)
309 return "~" + virtualPath.Substring (appPath_lenght);
314 static char [] path_sep = { '/' };
316 static string Normalize (string path)
318 if (!IsRooted (path))
319 throw new ArgumentException (String.Format ("The relative virtual path '{0}' is not allowed here.", path));
321 if (path.Length == 1) // '/' or '~'
324 path = Canonize (path);
326 int dotPos = path.IndexOf ('.');
327 while (dotPos >= 0) {
328 if (++dotPos == path.Length)
331 char nextChar = path [dotPos];
333 if ((nextChar == '/') || (nextChar == '.'))
336 dotPos = path.IndexOf ('.', dotPos);
342 bool starts_with_tilda = false;
343 bool ends_with_slash = false;
344 string [] apppath_parts= null;
346 if (path [0] == '~') {
347 if (path.Length == 2) // "~/"
349 starts_with_tilda = true;
350 path = path.Substring (1);
352 else if (path.Length == 1) { // "/"
356 if (path [path.Length - 1] == '/')
357 ends_with_slash = true;
359 string [] parts = StrUtils.SplitRemoveEmptyEntries (path, path_sep);
360 int end = parts.Length;
364 for (int i = 0; i < end; i++) {
365 string current = parts [i];
369 if (current == "..") {
375 if (starts_with_tilda) {
376 if (apppath_parts == null) {
377 string apppath = HttpRuntime.AppDomainAppVirtualPath;
378 apppath_parts = StrUtils.SplitRemoveEmptyEntries (apppath, path_sep);
381 if ((apppath_parts.Length + dest) >= 0)
385 throw new HttpException ("Cannot use a leading .. to exit above the top directory.");
389 parts [dest] = current;
391 apppath_parts [apppath_parts.Length + dest] = current;
396 StringBuilder str = new StringBuilder();
397 if (apppath_parts != null) {
398 starts_with_tilda = false;
399 int count = apppath_parts.Length;
402 for (int i = 0; i < count; i++) {
404 str.Append (apppath_parts [i]);
407 else if (starts_with_tilda) {
411 for (int i = 0; i < dest; i++) {
413 str.Append (parts [i]);
416 if (str.Length > 0) {
424 return str.ToString ();
427 internal static string Canonize (string path)
430 for (int i=0; i < path.Length; i++) {
431 if ((path [i] == '\\') || (path [i] == '/' && (i + 1) < path.Length && (path [i + 1] == '/' || path [i + 1] == '\\'))) {
439 StringBuilder sb = new StringBuilder (path.Length);
440 sb.Append (path, 0, index);
442 for (int i = index; i < path.Length; i++) {
443 if (path [i] == '\\' || path [i] == '/') {
445 if (next < path.Length && (path [next] == '\\' || path [next] == '/'))
450 sb.Append (path [i]);
454 return sb.ToString ();
457 // See: http://support.microsoft.com/kb/932552
458 static readonly char[] invalidVirtualPathChars = {':', '*'};
459 internal static bool IsValidVirtualPath (string path)
464 return path.IndexOfAny (invalidVirtualPathChars) == -1;