Path.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. //------------------------------------------------------------------------------
  2. //
  3. // System.IO.Path.cs
  4. //
  5. // Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
  6. // Copyright (C) 2002 Ximian, Inc. (http://www.ximian.com)
  7. // Copyright (C) 2003 Ben Maurer
  8. //
  9. // Author: Jim Richardson, [email protected]
  10. // Dan Lewis ([email protected])
  11. // Gonzalo Paniagua Javier ([email protected])
  12. // Ben Maurer ([email protected])
  13. // Sebastien Pouliot <[email protected]>
  14. // Created: Saturday, August 11, 2001
  15. //
  16. //------------------------------------------------------------------------------
  17. //
  18. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  19. //
  20. // Permission is hereby granted, free of charge, to any person obtaining
  21. // a copy of this software and associated documentation files (the
  22. // "Software"), to deal in the Software without restriction, including
  23. // without limitation the rights to use, copy, modify, merge, publish,
  24. // distribute, sublicense, and/or sell copies of the Software, and to
  25. // permit persons to whom the Software is furnished to do so, subject to
  26. // the following conditions:
  27. //
  28. // The above copyright notice and this permission notice shall be
  29. // included in all copies or substantial portions of the Software.
  30. //
  31. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  32. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  33. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  34. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  35. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  36. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  37. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  38. //
  39. using System.Globalization;
  40. using System.Runtime.CompilerServices;
  41. using System.Runtime.InteropServices;
  42. using System.Security;
  43. using System.Security.Cryptography;
  44. using System.Security.Permissions;
  45. using System.Text;
  46. namespace System.IO {
  47. [ComVisible (true)]
  48. public static class Path {
  49. [Obsolete ("see GetInvalidPathChars and GetInvalidFileNameChars methods.")]
  50. public static readonly char[] InvalidPathChars;
  51. public static readonly char AltDirectorySeparatorChar;
  52. public static readonly char DirectorySeparatorChar;
  53. public static readonly char PathSeparator;
  54. internal static readonly string DirectorySeparatorStr;
  55. public static readonly char VolumeSeparatorChar;
  56. internal static readonly char[] PathSeparatorChars;
  57. private static readonly bool dirEqualsVolume;
  58. // class methods
  59. public static string ChangeExtension (string path, string extension)
  60. {
  61. if (path == null)
  62. return null;
  63. if (path.IndexOfAny (InvalidPathChars) != -1)
  64. throw new ArgumentException ("Illegal characters in path.");
  65. int iExt = findExtension (path);
  66. if (extension == null)
  67. return iExt < 0 ? path : path.Substring (0, iExt);
  68. else if (extension.Length == 0)
  69. return iExt < 0 ? path + '.' : path.Substring (0, iExt + 1);
  70. else if (path.Length != 0) {
  71. if (extension.Length > 0 && extension [0] != '.')
  72. extension = "." + extension;
  73. } else
  74. extension = String.Empty;
  75. if (iExt < 0) {
  76. return path + extension;
  77. } else if (iExt > 0) {
  78. string temp = path.Substring (0, iExt);
  79. return temp + extension;
  80. }
  81. return extension;
  82. }
  83. public static string Combine (string path1, string path2)
  84. {
  85. if (path1 == null)
  86. throw new ArgumentNullException ("path1");
  87. if (path2 == null)
  88. throw new ArgumentNullException ("path2");
  89. if (path1.Length == 0)
  90. return path2;
  91. if (path2.Length == 0)
  92. return path1;
  93. if (path1.IndexOfAny (InvalidPathChars) != -1)
  94. throw new ArgumentException ("Illegal characters in path.");
  95. if (path2.IndexOfAny (InvalidPathChars) != -1)
  96. throw new ArgumentException ("Illegal characters in path.");
  97. //TODO???: UNC names
  98. if (IsPathRooted (path2))
  99. return path2;
  100. char p1end = path1 [path1.Length - 1];
  101. if (p1end != DirectorySeparatorChar && p1end != AltDirectorySeparatorChar && p1end != VolumeSeparatorChar)
  102. return path1 + DirectorySeparatorStr + path2;
  103. return path1 + path2;
  104. }
  105. //
  106. // This routine:
  107. // * Removes duplicat path separators from a string
  108. // * If the string starts with \\, preserves the first two (hostname on Windows)
  109. // * Removes the trailing path separator.
  110. // * Returns the DirectorySeparatorChar for the single input DirectorySeparatorChar or AltDirectorySeparatorChar
  111. //
  112. // Unlike CanonicalizePath, this does not do any path resolution
  113. // (which GetDirectoryName is not supposed to do).
  114. //
  115. internal static string CleanPath (string s)
  116. {
  117. int l = s.Length;
  118. int sub = 0;
  119. int start = 0;
  120. // Host prefix?
  121. char s0 = s [0];
  122. if (l > 2 && s0 == '\\' && s [1] == '\\'){
  123. start = 2;
  124. }
  125. // We are only left with root
  126. if (l == 1 && (s0 == DirectorySeparatorChar || s0 == AltDirectorySeparatorChar))
  127. return s;
  128. // Cleanup
  129. for (int i = start; i < l; i++){
  130. char c = s [i];
  131. if (c != DirectorySeparatorChar && c != AltDirectorySeparatorChar)
  132. continue;
  133. if (i+1 == l)
  134. sub++;
  135. else {
  136. c = s [i + 1];
  137. if (c == DirectorySeparatorChar || c == AltDirectorySeparatorChar)
  138. sub++;
  139. }
  140. }
  141. if (sub == 0)
  142. return s;
  143. char [] copy = new char [l-sub];
  144. if (start != 0){
  145. copy [0] = '\\';
  146. copy [1] = '\\';
  147. }
  148. for (int i = start, j = start; i < l && j < copy.Length; i++){
  149. char c = s [i];
  150. if (c != DirectorySeparatorChar && c != AltDirectorySeparatorChar){
  151. copy [j++] = c;
  152. continue;
  153. }
  154. // For non-trailing cases.
  155. if (j+1 != copy.Length){
  156. copy [j++] = DirectorySeparatorChar;
  157. for (;i < l-1; i++){
  158. c = s [i+1];
  159. if (c != DirectorySeparatorChar && c != AltDirectorySeparatorChar)
  160. break;
  161. }
  162. }
  163. }
  164. return new String (copy);
  165. }
  166. public static string GetDirectoryName (string path)
  167. {
  168. // LAMESPEC: For empty string MS docs say both
  169. // return null AND throw exception. Seems .NET throws.
  170. if (path == String.Empty)
  171. throw new ArgumentException("Invalid path");
  172. if (path == null || GetPathRoot (path) == path)
  173. return null;
  174. if (path.Trim ().Length == 0)
  175. throw new ArgumentException ("Argument string consists of whitespace characters only.");
  176. if (path.IndexOfAny (System.IO.Path.InvalidPathChars) > -1)
  177. throw new ArgumentException ("Path contains invalid characters");
  178. int nLast = path.LastIndexOfAny (PathSeparatorChars);
  179. if (nLast == 0)
  180. nLast++;
  181. if (nLast > 0) {
  182. string ret = path.Substring (0, nLast);
  183. int l = ret.Length;
  184. if (l >= 2 && DirectorySeparatorChar == '\\' && ret [l - 1] == VolumeSeparatorChar)
  185. return ret + DirectorySeparatorChar;
  186. else {
  187. //
  188. // Important: do not use CanonicalizePath here, use
  189. // the custom CleanPath here, as this should not
  190. // return absolute paths
  191. //
  192. return CleanPath (ret);
  193. }
  194. }
  195. return String.Empty;
  196. }
  197. public static string GetExtension (string path)
  198. {
  199. if (path == null)
  200. return null;
  201. if (path.IndexOfAny (InvalidPathChars) != -1)
  202. throw new ArgumentException ("Illegal characters in path.");
  203. int iExt = findExtension (path);
  204. if (iExt > -1)
  205. {
  206. if (iExt < path.Length - 1)
  207. return path.Substring (iExt);
  208. }
  209. return string.Empty;
  210. }
  211. public static string GetFileName (string path)
  212. {
  213. if (path == null || path.Length == 0)
  214. return path;
  215. if (path.IndexOfAny (InvalidPathChars) != -1)
  216. throw new ArgumentException ("Illegal characters in path.");
  217. int nLast = path.LastIndexOfAny (PathSeparatorChars);
  218. if (nLast >= 0)
  219. return path.Substring (nLast + 1);
  220. return path;
  221. }
  222. public static string GetFileNameWithoutExtension (string path)
  223. {
  224. return ChangeExtension (GetFileName (path), null);
  225. }
  226. public static string GetFullPath (string path)
  227. {
  228. string fullpath = InsecureGetFullPath (path);
  229. #if !NET_2_1
  230. if (SecurityManager.SecurityEnabled) {
  231. new FileIOPermission (FileIOPermissionAccess.PathDiscovery, fullpath).Demand ();
  232. }
  233. #endif
  234. return fullpath;
  235. }
  236. internal static string WindowsDriveAdjustment (string path)
  237. {
  238. // two special cases to consider when a drive is specified
  239. if (path.Length < 2)
  240. return path;
  241. if ((path [1] != ':') || !Char.IsLetter (path [0]))
  242. return path;
  243. string current = Directory.GetCurrentDirectory ();
  244. // first, only the drive is specified
  245. if (path.Length == 2) {
  246. // then if the current directory is on the same drive
  247. if (current [0] == path [0])
  248. path = current; // we return it
  249. else
  250. path += '\\';
  251. } else if ((path [2] != Path.DirectorySeparatorChar) && (path [2] != Path.AltDirectorySeparatorChar)) {
  252. // second, the drive + a directory is specified *without* a separator between them (e.g. C:dir).
  253. // If the current directory is on the specified drive...
  254. if (current [0] == path [0]) {
  255. // then specified directory is appended to the current drive directory
  256. path = Path.Combine (current, path.Substring (2, path.Length - 2));
  257. } else {
  258. // if not, then just pretend there was a separator (Path.Combine won't work in this case)
  259. path = String.Concat (path.Substring (0, 2), DirectorySeparatorStr, path.Substring (2, path.Length - 2));
  260. }
  261. }
  262. return path;
  263. }
  264. // insecure - do not call directly
  265. internal static string InsecureGetFullPath (string path)
  266. {
  267. if (path == null)
  268. throw new ArgumentNullException ("path");
  269. if (path.Trim ().Length == 0) {
  270. string msg = Locale.GetText ("The specified path is not of a legal form (empty).");
  271. throw new ArgumentException (msg);
  272. }
  273. // adjust for drives, i.e. a special case for windows
  274. if (Environment.IsRunningOnWindows)
  275. path = WindowsDriveAdjustment (path);
  276. // if the supplied path ends with a separator...
  277. char end = path [path.Length - 1];
  278. if (path.Length >= 2 &&
  279. IsDsc (path [0]) &&
  280. IsDsc (path [1])) {
  281. if (path.Length == 2 || path.IndexOf (path [0], 2) < 0)
  282. throw new ArgumentException ("UNC pass should be of the form \\\\server\\share.");
  283. if (path [0] != DirectorySeparatorChar)
  284. path = path.Replace (AltDirectorySeparatorChar, DirectorySeparatorChar);
  285. path = CanonicalizePath (path);
  286. } else {
  287. if (!IsPathRooted (path))
  288. path = Directory.GetCurrentDirectory () + DirectorySeparatorStr + path;
  289. else if (DirectorySeparatorChar == '\\' &&
  290. path.Length >= 2 &&
  291. IsDsc (path [0]) &&
  292. !IsDsc (path [1])) { // like `\abc\def'
  293. string current = Directory.GetCurrentDirectory ();
  294. if (current [1] == VolumeSeparatorChar)
  295. path = current.Substring (0, 2) + path;
  296. else
  297. path = current.Substring (0, current.IndexOf ('\\', current.IndexOf ("\\\\") + 1));
  298. }
  299. path = CanonicalizePath (path);
  300. }
  301. // if the original ended with a [Alt]DirectorySeparatorChar then ensure the full path also ends with one
  302. if (IsDsc (end) && (path [path.Length - 1] != DirectorySeparatorChar))
  303. path += DirectorySeparatorChar;
  304. return path;
  305. }
  306. static bool IsDsc (char c) {
  307. return c == DirectorySeparatorChar || c == AltDirectorySeparatorChar;
  308. }
  309. public static string GetPathRoot (string path)
  310. {
  311. if (path == null)
  312. return null;
  313. if (path.Trim ().Length == 0)
  314. throw new ArgumentException ("The specified path is not of a legal form.");
  315. if (!IsPathRooted (path))
  316. return String.Empty;
  317. if (DirectorySeparatorChar == '/') {
  318. // UNIX
  319. return IsDsc (path [0]) ? DirectorySeparatorStr : String.Empty;
  320. } else {
  321. // Windows
  322. int len = 2;
  323. if (path.Length == 1 && IsDsc (path [0]))
  324. return DirectorySeparatorStr;
  325. else if (path.Length < 2)
  326. return String.Empty;
  327. if (IsDsc (path [0]) && IsDsc (path[1])) {
  328. // UNC: \\server or \\server\share
  329. // Get server
  330. while (len < path.Length && !IsDsc (path [len])) len++;
  331. // Get share
  332. if (len < path.Length) {
  333. len++;
  334. while (len < path.Length && !IsDsc (path [len])) len++;
  335. }
  336. return DirectorySeparatorStr +
  337. DirectorySeparatorStr +
  338. path.Substring (2, len - 2).Replace (AltDirectorySeparatorChar, DirectorySeparatorChar);
  339. } else if (IsDsc (path [0])) {
  340. // path starts with '\' or '/'
  341. return DirectorySeparatorStr;
  342. } else if (path[1] == VolumeSeparatorChar) {
  343. // C:\folder
  344. if (path.Length >= 3 && (IsDsc (path [2]))) len++;
  345. } else
  346. return Directory.GetCurrentDirectory ().Substring (0, 2);// + path.Substring (0, len);
  347. return path.Substring (0, len);
  348. }
  349. }
  350. // FIXME: Further limit the assertion when imperative Assert is implemented
  351. [FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
  352. public static string GetTempFileName ()
  353. {
  354. FileStream f = null;
  355. string path;
  356. Random rnd;
  357. int num = 0;
  358. rnd = new Random ();
  359. do {
  360. num = rnd.Next ();
  361. num++;
  362. path = Path.Combine (GetTempPath(), "tmp" + num.ToString("x") + ".tmp");
  363. try {
  364. f = new FileStream (path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read,
  365. 8192, false, (FileOptions) 1);
  366. }
  367. catch (SecurityException) {
  368. // avoid an endless loop
  369. throw;
  370. }
  371. catch {
  372. }
  373. } while (f == null);
  374. f.Close();
  375. return path;
  376. }
  377. [EnvironmentPermission (SecurityAction.Demand, Unrestricted = true)]
  378. public static string GetTempPath ()
  379. {
  380. string p = get_temp_path ();
  381. if (p.Length > 0 && p [p.Length - 1] != DirectorySeparatorChar)
  382. return p + DirectorySeparatorChar;
  383. return p;
  384. }
  385. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  386. private static extern string get_temp_path ();
  387. public static bool HasExtension (string path)
  388. {
  389. if (path == null || path.Trim ().Length == 0)
  390. return false;
  391. if (path.IndexOfAny (InvalidPathChars) != -1)
  392. throw new ArgumentException ("Illegal characters in path.");
  393. int pos = findExtension (path);
  394. return 0 <= pos && pos < path.Length - 1;
  395. }
  396. public static bool IsPathRooted (string path)
  397. {
  398. if (path == null || path.Length == 0)
  399. return false;
  400. if (path.IndexOfAny (InvalidPathChars) != -1)
  401. throw new ArgumentException ("Illegal characters in path.");
  402. char c = path [0];
  403. return (c == DirectorySeparatorChar ||
  404. c == AltDirectorySeparatorChar ||
  405. (!dirEqualsVolume && path.Length > 1 && path [1] == VolumeSeparatorChar));
  406. }
  407. public static char[] GetInvalidFileNameChars ()
  408. {
  409. // return a new array as we do not want anyone to be able to change the values
  410. if (Environment.IsRunningOnWindows) {
  411. return new char [41] { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  412. '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12',
  413. '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D',
  414. '\x1E', '\x1F', '\x22', '\x3C', '\x3E', '\x7C', ':', '*', '?', '\\', '/' };
  415. } else {
  416. return new char [2] { '\x00', '/' };
  417. }
  418. }
  419. public static char[] GetInvalidPathChars ()
  420. {
  421. // return a new array as we do not want anyone to be able to change the values
  422. if (Environment.IsRunningOnWindows) {
  423. return new char [36] { '\x22', '\x3C', '\x3E', '\x7C', '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  424. '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12',
  425. '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D',
  426. '\x1E', '\x1F' };
  427. } else {
  428. return new char [1] { '\x00' };
  429. }
  430. }
  431. public static string GetRandomFileName ()
  432. {
  433. // returns a 8.3 filename (total size 12)
  434. StringBuilder sb = new StringBuilder (12);
  435. // using strong crypto but without creating the file
  436. RandomNumberGenerator rng = RandomNumberGenerator.Create ();
  437. byte [] buffer = new byte [11];
  438. rng.GetBytes (buffer);
  439. for (int i = 0; i < buffer.Length; i++) {
  440. if (sb.Length == 8)
  441. sb.Append ('.');
  442. // restrict to length of range [a..z0..9]
  443. int b = (buffer [i] % 36);
  444. char c = (char) (b < 26 ? (b + 'a') : (b - 26 + '0'));
  445. sb.Append (c);
  446. }
  447. return sb.ToString ();
  448. }
  449. // private class methods
  450. private static int findExtension (string path)
  451. {
  452. // method should return the index of the path extension
  453. // start or -1 if no valid extension
  454. if (path != null){
  455. int iLastDot = path.LastIndexOf ('.');
  456. int iLastSep = path.LastIndexOfAny ( PathSeparatorChars );
  457. if (iLastDot > iLastSep)
  458. return iLastDot;
  459. }
  460. return -1;
  461. }
  462. static Path ()
  463. {
  464. VolumeSeparatorChar = MonoIO.VolumeSeparatorChar;
  465. DirectorySeparatorChar = MonoIO.DirectorySeparatorChar;
  466. AltDirectorySeparatorChar = MonoIO.AltDirectorySeparatorChar;
  467. PathSeparator = MonoIO.PathSeparator;
  468. // this copy will be modifiable ("by design")
  469. InvalidPathChars = GetInvalidPathChars ();
  470. // internal fields
  471. DirectorySeparatorStr = DirectorySeparatorChar.ToString ();
  472. PathSeparatorChars = new char [] {
  473. DirectorySeparatorChar,
  474. AltDirectorySeparatorChar,
  475. VolumeSeparatorChar
  476. };
  477. dirEqualsVolume = (DirectorySeparatorChar == VolumeSeparatorChar);
  478. }
  479. // returns the server and share part of a UNC. Assumes "path" is a UNC.
  480. static string GetServerAndShare (string path)
  481. {
  482. int len = 2;
  483. while (len < path.Length && !IsDsc (path [len])) len++;
  484. if (len < path.Length) {
  485. len++;
  486. while (len < path.Length && !IsDsc (path [len])) len++;
  487. }
  488. return path.Substring (2, len - 2).Replace (AltDirectorySeparatorChar, DirectorySeparatorChar);
  489. }
  490. // assumes Environment.IsRunningOnWindows == true
  491. static bool SameRoot (string root, string path)
  492. {
  493. // compare root - if enough details are available
  494. if ((root.Length < 2) || (path.Length < 2))
  495. return false;
  496. // UNC handling
  497. if (IsDsc (root[0]) && IsDsc (root[1])) {
  498. if (!(IsDsc (path[0]) && IsDsc (path[1])))
  499. return false;
  500. string rootShare = GetServerAndShare (root);
  501. string pathShare = GetServerAndShare (path);
  502. return String.Compare (rootShare, pathShare, true, CultureInfo.InvariantCulture) == 0;
  503. }
  504. // same volume/drive
  505. if (!root [0].Equals (path [0]))
  506. return false;
  507. // presence of the separator
  508. if (path[1] != Path.VolumeSeparatorChar)
  509. return false;
  510. if ((root.Length > 2) && (path.Length > 2)) {
  511. // but don't directory compare the directory separator
  512. return (IsDsc (root[2]) && IsDsc (path[2]));
  513. }
  514. return true;
  515. }
  516. static string CanonicalizePath (string path)
  517. {
  518. // STEP 1: Check for empty string
  519. if (path == null)
  520. return path;
  521. if (Environment.IsRunningOnWindows)
  522. path = path.Trim ();
  523. if (path.Length == 0)
  524. return path;
  525. // STEP 2: Check to see if this is only a root
  526. string root = Path.GetPathRoot (path);
  527. // it will return '\' for path '\', while it should return 'c:\' or so.
  528. // Note: commenting this out makes the need for the (target == 1...) check in step 5
  529. //if (root == path) return path;
  530. // STEP 3: split the directories, this gets rid of consecutative "/"'s
  531. string[] dirs = path.Split (Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
  532. // STEP 4: Get rid of directories containing . and ..
  533. int target = 0;
  534. bool isUnc = Environment.IsRunningOnWindows &&
  535. root.Length > 2 && IsDsc (root[0]) && IsDsc (root[1]);
  536. // Set an overwrite limit for UNC paths since '\' + server + share
  537. // must not be eliminated by the '..' elimination algorithm.
  538. int limit = isUnc ? 3 : 0;
  539. for (int i = 0; i < dirs.Length; i++) {
  540. // WIN32 path components must be trimmed
  541. if (Environment.IsRunningOnWindows)
  542. dirs[i] = dirs[i].TrimEnd ();
  543. if (dirs[i] == "." || (i != 0 && dirs[i].Length == 0))
  544. continue;
  545. else if (dirs[i] == "..") {
  546. // don't overwrite path segments below the limit
  547. if (target > limit)
  548. target--;
  549. } else
  550. dirs[target++] = dirs[i];
  551. }
  552. // STEP 5: Combine everything.
  553. if (target == 0 || (target == 1 && dirs[0] == ""))
  554. return root;
  555. else {
  556. string ret = String.Join (DirectorySeparatorStr, dirs, 0, target);
  557. if (Environment.IsRunningOnWindows) {
  558. // append leading '\' of the UNC path that was lost in STEP 3.
  559. if (isUnc)
  560. ret = Path.DirectorySeparatorStr + ret;
  561. if (!SameRoot (root, ret))
  562. ret = root + ret;
  563. if (isUnc) {
  564. return ret;
  565. } else if (!IsDsc (path[0]) && SameRoot (root, path)) {
  566. if (ret.Length <= 2 && !ret.EndsWith (DirectorySeparatorStr)) // '\' after "c:"
  567. ret += Path.DirectorySeparatorChar;
  568. return ret;
  569. } else {
  570. string current = Directory.GetCurrentDirectory ();
  571. if (current.Length > 1 && current[1] == Path.VolumeSeparatorChar) {
  572. // DOS local file path
  573. if (ret.Length == 0 || IsDsc (ret[0]))
  574. ret += '\\';
  575. return current.Substring (0, 2) + ret;
  576. } else if (IsDsc (current[current.Length - 1]) && IsDsc (ret[0]))
  577. return current + ret.Substring (1);
  578. else
  579. return current + ret;
  580. }
  581. }
  582. return ret;
  583. }
  584. }
  585. // required for FileIOPermission (and most proibably reusable elsewhere too)
  586. // both path MUST be "full paths"
  587. static internal bool IsPathSubsetOf (string subset, string path)
  588. {
  589. if (subset.Length > path.Length)
  590. return false;
  591. // check that everything up to the last separator match
  592. int slast = subset.LastIndexOfAny (PathSeparatorChars);
  593. if (String.Compare (subset, 0, path, 0, slast) != 0)
  594. return false;
  595. slast++;
  596. // then check if the last segment is identical
  597. int plast = path.IndexOfAny (PathSeparatorChars, slast);
  598. if (plast >= slast) {
  599. return String.Compare (subset, slast, path, slast, path.Length - plast) == 0;
  600. }
  601. if (subset.Length != path.Length)
  602. return false;
  603. return String.Compare (subset, slast, path, slast, subset.Length - slast) == 0;
  604. }
  605. #if NET_4_0
  606. public static string Combine (params string [] paths)
  607. {
  608. if (paths == null)
  609. throw new ArgumentNullException ("paths");
  610. int l = 0;
  611. bool need_sep = false;
  612. foreach (var s in paths){
  613. if (s == null)
  614. throw new ArgumentNullException ("One of the paths contains a null value", "paths");
  615. if (s.IndexOfAny (InvalidPathChars) != -1)
  616. throw new ArgumentException ("Illegal characters in path.");
  617. if (l == 0 && s.Length > 0){
  618. char p1end = s [s.Length - 1];
  619. if (p1end != DirectorySeparatorChar && p1end != AltDirectorySeparatorChar && p1end != VolumeSeparatorChar){
  620. need_sep = true;
  621. l += DirectorySeparatorStr.Length;
  622. }
  623. }
  624. l += s.Length;
  625. }
  626. var ret = new StringBuilder (l);
  627. l = 0;
  628. foreach (var s in paths){
  629. ret.Append (s);
  630. if (l == 0 && need_sep)
  631. ret.Append (DirectorySeparatorStr);
  632. l = 1;
  633. }
  634. return ret.ToString ();
  635. }
  636. #endif
  637. }
  638. }