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 private 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)
294 Console.WriteLine ("VirtualPathUtility.ToAppRelative (\"{0}\", \"{1}\")", virtualPath, applicationPath);
296 virtualPath = Normalize (virtualPath);
298 Console.WriteLine ("\tvirtualPath (normalized): {0}", virtualPath);
300 if (IsAppRelative (virtualPath))
303 if (!IsAbsolute (applicationPath))
304 throw new ArgumentException ("appPath is not absolute", "applicationPath");
306 applicationPath = Normalize (applicationPath);
308 if (applicationPath.Length == 1)
309 return "~" + virtualPath;
311 int appPath_lenght = applicationPath.Length;
312 if (String.CompareOrdinal (virtualPath, applicationPath) == 0)
314 if (String.CompareOrdinal (virtualPath, 0, applicationPath, 0, appPath_lenght) == 0)
315 return "~" + virtualPath.Substring (appPath_lenght);
320 static char [] path_sep = { '/' };
322 static string Normalize (string path)
324 if (!IsRooted (path))
325 throw new ArgumentException (String.Format ("The relative virtual path '{0}' is not allowed here.", path));
327 if (path.Length == 1) // '/' or '~'
330 path = Canonize (path);
332 int dotPos = path.IndexOf ('.');
333 while (dotPos >= 0) {
334 if (++dotPos == path.Length)
337 char nextChar = path [dotPos];
339 if ((nextChar == '/') || (nextChar == '.'))
342 dotPos = path.IndexOf ('.', dotPos);
348 bool starts_with_tilda = false;
349 bool ends_with_slash = false;
350 string [] apppath_parts= null;
352 if (path [0] == '~') {
353 if (path.Length == 2) // "~/"
355 starts_with_tilda = true;
356 path = path.Substring (1);
358 else if (path.Length == 1) { // "/"
362 if (path [path.Length - 1] == '/')
363 ends_with_slash = true;
365 string [] parts = StrUtils.SplitRemoveEmptyEntries (path, path_sep);
366 int end = parts.Length;
370 for (int i = 0; i < end; i++) {
371 string current = parts [i];
375 if (current == "..") {
381 if (starts_with_tilda) {
382 if (apppath_parts == null) {
383 string apppath = HttpRuntime.AppDomainAppVirtualPath;
384 apppath_parts = StrUtils.SplitRemoveEmptyEntries (apppath, path_sep);
387 if ((apppath_parts.Length + dest) >= 0)
391 throw new HttpException ("Cannot use a leading .. to exit above the top directory.");
395 parts [dest] = current;
397 apppath_parts [apppath_parts.Length + dest] = current;
402 StringBuilder str = new StringBuilder();
403 if (apppath_parts != null) {
404 starts_with_tilda = false;
405 int count = apppath_parts.Length;
408 for (int i = 0; i < count; i++) {
410 str.Append (apppath_parts [i]);
413 else if (starts_with_tilda) {
417 for (int i = 0; i < dest; i++) {
419 str.Append (parts [i]);
422 if (str.Length > 0) {
430 return str.ToString ();
433 static string Canonize (string path)
436 for (int i=0; i < path.Length; i++) {
437 if ((path [i] == '\\') || (path [i] == '/' && (i + 1) < path.Length && (path [i + 1] == '/' || path [i + 1] == '\\'))) {
445 StringBuilder sb = new StringBuilder (path.Length);
446 sb.Append (path, 0, index);
448 for (int i = index; i < path.Length; i++) {
449 if (path [i] == '\\' || path [i] == '/') {
451 if (next < path.Length && (path [next] == '\\' || path [next] == '/'))
456 sb.Append (path [i]);
460 return sb.ToString ();