PathUtil.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // System.Web.Util.PathUtil
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System;
  10. using System.Collections;
  11. using System.IO;
  12. using System.Reflection;
  13. namespace System.Web.Util
  14. {
  15. internal class PathUtil
  16. {
  17. static string appbase;
  18. static char [] separators;
  19. static PathUtil ()
  20. {
  21. // This hack is a workaround until AppDomainVirtualPath works... Gotta investigate it.
  22. Assembly entry = Assembly.GetEntryAssembly ();
  23. appbase = Path.GetDirectoryName (entry.Location);
  24. //
  25. if (Path.DirectorySeparatorChar != Path.AltDirectorySeparatorChar)
  26. separators = new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar};
  27. else
  28. separators = new char [] {Path.DirectorySeparatorChar};
  29. }
  30. static string MakeAbsolute (string abspath)
  31. {
  32. string [] parts = abspath.Split (separators);
  33. ArrayList valid = new ArrayList ();
  34. int len = parts.Length;
  35. bool hasDots = false;
  36. for (int i = 0; i < len; i++) {
  37. if (parts [i] == ".") {
  38. hasDots = true;
  39. continue;
  40. }
  41. if (parts [i] == "..") {
  42. hasDots = true;
  43. if (valid.Count > 0)
  44. valid.RemoveAt (valid.Count - 1);
  45. continue;
  46. }
  47. valid.Add (parts [i]);
  48. }
  49. if (!hasDots)
  50. return abspath;
  51. parts = (String []) valid.ToArray (typeof (string));
  52. string result = String.Join (new String (Path.DirectorySeparatorChar, 1), parts);
  53. if (!Path.IsPathRooted (result))
  54. return Path.DirectorySeparatorChar + result;
  55. return result;
  56. }
  57. static public string Combine (string basepath, string relative)
  58. {
  59. if (relative == null || relative.Length == 0)
  60. throw new ArgumentException ("empty or null", "relative");
  61. char first = relative [0];
  62. if (first == '/' || first == '\\' || Path.IsPathRooted (relative))
  63. throw new ArgumentException ("'relative' is rooted", "relative");
  64. if (first == '~' && relative.Length > 1 && Array.IndexOf (separators, relative [1]) != -1)
  65. return Path.Combine (appbase, relative.Substring (2));
  66. if (basepath == null)
  67. basepath = appbase;
  68. return MakeAbsolute (Path.Combine (basepath, relative));
  69. }
  70. }
  71. }