Path.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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. var canonicalize = true;
  279. if (path.Length >= 2 &&
  280. IsDsc (path [0]) &&
  281. IsDsc (path [1])) {
  282. if (path.Length == 2 || path.IndexOf (path [0], 2) < 0)
  283. throw new ArgumentException ("UNC pass should be of the form \\\\server\\share.");
  284. if (path [0] != DirectorySeparatorChar)
  285. path = path.Replace (AltDirectorySeparatorChar, DirectorySeparatorChar);
  286. } else {
  287. if (!IsPathRooted (path)) {
  288. // avoid calling expensive CanonicalizePath when possible
  289. var start = 0;
  290. while ((start = path.IndexOf ('.', start)) != -1) {
  291. if (++start == path.Length || path [start] == DirectorySeparatorChar || path [start] == AltDirectorySeparatorChar)
  292. break;
  293. }
  294. canonicalize = start > 0;
  295. path = Directory.GetCurrentDirectory () + DirectorySeparatorStr + path;
  296. } else if (DirectorySeparatorChar == '\\' &&
  297. path.Length >= 2 &&
  298. IsDsc (path [0]) &&
  299. !IsDsc (path [1])) { // like `\abc\def'
  300. string current = Directory.GetCurrentDirectory ();
  301. if (current [1] == VolumeSeparatorChar)
  302. path = current.Substring (0, 2) + path;
  303. else
  304. path = current.Substring (0, current.IndexOf ('\\', current.IndexOf ("\\\\") + 1));
  305. }
  306. }
  307. if (canonicalize)
  308. path = CanonicalizePath (path);
  309. // if the original ended with a [Alt]DirectorySeparatorChar then ensure the full path also ends with one
  310. if (IsDsc (end) && (path [path.Length - 1] != DirectorySeparatorChar))
  311. path += DirectorySeparatorChar;
  312. return path;
  313. }
  314. static bool IsDsc (char c) {
  315. return c == DirectorySeparatorChar || c == AltDirectorySeparatorChar;
  316. }
  317. public static string GetPathRoot (string path)
  318. {
  319. if (path == null)
  320. return null;
  321. if (path.Trim ().Length == 0)
  322. throw new ArgumentException ("The specified path is not of a legal form.");
  323. if (!IsPathRooted (path))
  324. return String.Empty;
  325. if (DirectorySeparatorChar == '/') {
  326. // UNIX
  327. return IsDsc (path [0]) ? DirectorySeparatorStr : String.Empty;
  328. } else {
  329. // Windows
  330. int len = 2;
  331. if (path.Length == 1 && IsDsc (path [0]))
  332. return DirectorySeparatorStr;
  333. else if (path.Length < 2)
  334. return String.Empty;
  335. if (IsDsc (path [0]) && IsDsc (path[1])) {
  336. // UNC: \\server or \\server\share
  337. // Get server
  338. while (len < path.Length && !IsDsc (path [len])) len++;
  339. // Get share
  340. if (len < path.Length) {
  341. len++;
  342. while (len < path.Length && !IsDsc (path [len])) len++;
  343. }
  344. return DirectorySeparatorStr +
  345. DirectorySeparatorStr +
  346. path.Substring (2, len - 2).Replace (AltDirectorySeparatorChar, DirectorySeparatorChar);
  347. } else if (IsDsc (path [0])) {
  348. // path starts with '\' or '/'
  349. return DirectorySeparatorStr;
  350. } else if (path[1] == VolumeSeparatorChar) {
  351. // C:\folder
  352. if (path.Length >= 3 && (IsDsc (path [2]))) len++;
  353. } else
  354. return Directory.GetCurrentDirectory ().Substring (0, 2);// + path.Substring (0, len);
  355. return path.Substring (0, len);
  356. }
  357. }
  358. // FIXME: Further limit the assertion when imperative Assert is implemented
  359. [FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
  360. public static string GetTempFileName ()
  361. {
  362. FileStream f = null;
  363. string path;
  364. Random rnd;
  365. int num = 0;
  366. rnd = new Random ();
  367. do {
  368. num = rnd.Next ();
  369. num++;
  370. path = Path.Combine (GetTempPath(), "tmp" + num.ToString("x") + ".tmp");
  371. try {
  372. f = new FileStream (path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read,
  373. 8192, false, (FileOptions) 1);
  374. }
  375. catch (SecurityException) {
  376. // avoid an endless loop
  377. throw;
  378. }
  379. catch {
  380. }
  381. } while (f == null);
  382. f.Close();
  383. return path;
  384. }
  385. [EnvironmentPermission (SecurityAction.Demand, Unrestricted = true)]
  386. public static string GetTempPath ()
  387. {
  388. string p = get_temp_path ();
  389. if (p.Length > 0 && p [p.Length - 1] != DirectorySeparatorChar)
  390. return p + DirectorySeparatorChar;
  391. return p;
  392. }
  393. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  394. private static extern string get_temp_path ();
  395. public static bool HasExtension (string path)
  396. {
  397. if (path == null || path.Trim ().Length == 0)
  398. return false;
  399. if (path.IndexOfAny (InvalidPathChars) != -1)
  400. throw new ArgumentException ("Illegal characters in path.");
  401. int pos = findExtension (path);
  402. return 0 <= pos && pos < path.Length - 1;
  403. }
  404. public static bool IsPathRooted (string path)
  405. {
  406. if (path == null || path.Length == 0)
  407. return false;
  408. if (path.IndexOfAny (InvalidPathChars) != -1)
  409. throw new ArgumentException ("Illegal characters in path.");
  410. char c = path [0];
  411. return (c == DirectorySeparatorChar ||
  412. c == AltDirectorySeparatorChar ||
  413. (!dirEqualsVolume && path.Length > 1 && path [1] == VolumeSeparatorChar));
  414. }
  415. public static char[] GetInvalidFileNameChars ()
  416. {
  417. // return a new array as we do not want anyone to be able to change the values
  418. if (Environment.IsRunningOnWindows) {
  419. return new char [41] { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  420. '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12',
  421. '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D',
  422. '\x1E', '\x1F', '\x22', '\x3C', '\x3E', '\x7C', ':', '*', '?', '\\', '/' };
  423. } else {
  424. return new char [2] { '\x00', '/' };
  425. }
  426. }
  427. public static char[] GetInvalidPathChars ()
  428. {
  429. // return a new array as we do not want anyone to be able to change the values
  430. if (Environment.IsRunningOnWindows) {
  431. return new char [36] { '\x22', '\x3C', '\x3E', '\x7C', '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  432. '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12',
  433. '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D',
  434. '\x1E', '\x1F' };
  435. } else {
  436. return new char [1] { '\x00' };
  437. }
  438. }
  439. public static string GetRandomFileName ()
  440. {
  441. // returns a 8.3 filename (total size 12)
  442. StringBuilder sb = new StringBuilder (12);
  443. // using strong crypto but without creating the file
  444. RandomNumberGenerator rng = RandomNumberGenerator.Create ();
  445. byte [] buffer = new byte [11];
  446. rng.GetBytes (buffer);
  447. for (int i = 0; i < buffer.Length; i++) {
  448. if (sb.Length == 8)
  449. sb.Append ('.');
  450. // restrict to length of range [a..z0..9]
  451. int b = (buffer [i] % 36);
  452. char c = (char) (b < 26 ? (b + 'a') : (b - 26 + '0'));
  453. sb.Append (c);
  454. }
  455. return sb.ToString ();
  456. }
  457. // private class methods
  458. private static int findExtension (string path)
  459. {
  460. // method should return the index of the path extension
  461. // start or -1 if no valid extension
  462. if (path != null){
  463. int iLastDot = path.LastIndexOf ('.');
  464. int iLastSep = path.LastIndexOfAny ( PathSeparatorChars );
  465. if (iLastDot > iLastSep)
  466. return iLastDot;
  467. }
  468. return -1;
  469. }
  470. static Path ()
  471. {
  472. VolumeSeparatorChar = MonoIO.VolumeSeparatorChar;
  473. DirectorySeparatorChar = MonoIO.DirectorySeparatorChar;
  474. AltDirectorySeparatorChar = MonoIO.AltDirectorySeparatorChar;
  475. PathSeparator = MonoIO.PathSeparator;
  476. // this copy will be modifiable ("by design")
  477. InvalidPathChars = GetInvalidPathChars ();
  478. // internal fields
  479. DirectorySeparatorStr = DirectorySeparatorChar.ToString ();
  480. PathSeparatorChars = new char [] {
  481. DirectorySeparatorChar,
  482. AltDirectorySeparatorChar,
  483. VolumeSeparatorChar
  484. };
  485. dirEqualsVolume = (DirectorySeparatorChar == VolumeSeparatorChar);
  486. }
  487. // returns the server and share part of a UNC. Assumes "path" is a UNC.
  488. static string GetServerAndShare (string path)
  489. {
  490. int len = 2;
  491. while (len < path.Length && !IsDsc (path [len])) len++;
  492. if (len < path.Length) {
  493. len++;
  494. while (len < path.Length && !IsDsc (path [len])) len++;
  495. }
  496. return path.Substring (2, len - 2).Replace (AltDirectorySeparatorChar, DirectorySeparatorChar);
  497. }
  498. // assumes Environment.IsRunningOnWindows == true
  499. static bool SameRoot (string root, string path)
  500. {
  501. // compare root - if enough details are available
  502. if ((root.Length < 2) || (path.Length < 2))
  503. return false;
  504. // UNC handling
  505. if (IsDsc (root[0]) && IsDsc (root[1])) {
  506. if (!(IsDsc (path[0]) && IsDsc (path[1])))
  507. return false;
  508. string rootShare = GetServerAndShare (root);
  509. string pathShare = GetServerAndShare (path);
  510. return String.Compare (rootShare, pathShare, true, CultureInfo.InvariantCulture) == 0;
  511. }
  512. // same volume/drive
  513. if (!root [0].Equals (path [0]))
  514. return false;
  515. // presence of the separator
  516. if (path[1] != Path.VolumeSeparatorChar)
  517. return false;
  518. if ((root.Length > 2) && (path.Length > 2)) {
  519. // but don't directory compare the directory separator
  520. return (IsDsc (root[2]) && IsDsc (path[2]));
  521. }
  522. return true;
  523. }
  524. static string CanonicalizePath (string path)
  525. {
  526. // STEP 1: Check for empty string
  527. if (path == null)
  528. return path;
  529. if (Environment.IsRunningOnWindows)
  530. path = path.Trim ();
  531. if (path.Length == 0)
  532. return path;
  533. // STEP 2: Check to see if this is only a root
  534. string root = Path.GetPathRoot (path);
  535. // it will return '\' for path '\', while it should return 'c:\' or so.
  536. // Note: commenting this out makes the need for the (target == 1...) check in step 5
  537. //if (root == path) return path;
  538. // STEP 3: split the directories, this gets rid of consecutative "/"'s
  539. string[] dirs = path.Split (Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
  540. // STEP 4: Get rid of directories containing . and ..
  541. int target = 0;
  542. bool isUnc = Environment.IsRunningOnWindows &&
  543. root.Length > 2 && IsDsc (root[0]) && IsDsc (root[1]);
  544. // Set an overwrite limit for UNC paths since '\' + server + share
  545. // must not be eliminated by the '..' elimination algorithm.
  546. int limit = isUnc ? 3 : 0;
  547. for (int i = 0; i < dirs.Length; i++) {
  548. // WIN32 path components must be trimmed
  549. if (Environment.IsRunningOnWindows)
  550. dirs[i] = dirs[i].TrimEnd ();
  551. if (dirs[i] == "." || (i != 0 && dirs[i].Length == 0))
  552. continue;
  553. else if (dirs[i] == "..") {
  554. // don't overwrite path segments below the limit
  555. if (target > limit)
  556. target--;
  557. } else
  558. dirs[target++] = dirs[i];
  559. }
  560. // STEP 5: Combine everything.
  561. if (target == 0 || (target == 1 && dirs[0] == ""))
  562. return root;
  563. else {
  564. string ret = String.Join (DirectorySeparatorStr, dirs, 0, target);
  565. if (Environment.IsRunningOnWindows) {
  566. // append leading '\' of the UNC path that was lost in STEP 3.
  567. if (isUnc)
  568. ret = Path.DirectorySeparatorStr + ret;
  569. if (!SameRoot (root, ret))
  570. ret = root + ret;
  571. if (isUnc) {
  572. return ret;
  573. } else if (!IsDsc (path[0]) && SameRoot (root, path)) {
  574. if (ret.Length <= 2 && !ret.EndsWith (DirectorySeparatorStr)) // '\' after "c:"
  575. ret += Path.DirectorySeparatorChar;
  576. return ret;
  577. } else {
  578. string current = Directory.GetCurrentDirectory ();
  579. if (current.Length > 1 && current[1] == Path.VolumeSeparatorChar) {
  580. // DOS local file path
  581. if (ret.Length == 0 || IsDsc (ret[0]))
  582. ret += '\\';
  583. return current.Substring (0, 2) + ret;
  584. } else if (IsDsc (current[current.Length - 1]) && IsDsc (ret[0]))
  585. return current + ret.Substring (1);
  586. else
  587. return current + ret;
  588. }
  589. }
  590. return ret;
  591. }
  592. }
  593. // required for FileIOPermission (and most proibably reusable elsewhere too)
  594. // both path MUST be "full paths"
  595. static internal bool IsPathSubsetOf (string subset, string path)
  596. {
  597. if (subset.Length > path.Length)
  598. return false;
  599. // check that everything up to the last separator match
  600. int slast = subset.LastIndexOfAny (PathSeparatorChars);
  601. if (String.Compare (subset, 0, path, 0, slast) != 0)
  602. return false;
  603. slast++;
  604. // then check if the last segment is identical
  605. int plast = path.IndexOfAny (PathSeparatorChars, slast);
  606. if (plast >= slast) {
  607. return String.Compare (subset, slast, path, slast, path.Length - plast) == 0;
  608. }
  609. if (subset.Length != path.Length)
  610. return false;
  611. return String.Compare (subset, slast, path, slast, subset.Length - slast) == 0;
  612. }
  613. #if NET_4_0
  614. public static string Combine (params string [] paths)
  615. {
  616. if (paths == null)
  617. throw new ArgumentNullException ("paths");
  618. int l = 0;
  619. bool need_sep = false;
  620. foreach (var s in paths){
  621. if (s == null)
  622. throw new ArgumentNullException ("One of the paths contains a null value", "paths");
  623. if (s.IndexOfAny (InvalidPathChars) != -1)
  624. throw new ArgumentException ("Illegal characters in path.");
  625. if (l == 0 && s.Length > 0){
  626. char p1end = s [s.Length - 1];
  627. if (p1end != DirectorySeparatorChar && p1end != AltDirectorySeparatorChar && p1end != VolumeSeparatorChar){
  628. need_sep = true;
  629. l += DirectorySeparatorStr.Length;
  630. }
  631. }
  632. }
  633. var ret = new StringBuilder (l);
  634. l = 0;
  635. foreach (var s in paths){
  636. if (IsPathRooted (s))
  637. ret.Length = l = 0;
  638. ret.Append (s);
  639. if (l == 0 && need_sep)
  640. ret.Append (DirectorySeparatorStr);
  641. l = 1;
  642. }
  643. return ret.ToString ();
  644. }
  645. public static string Combine (string path1, string path2, string path3)
  646. {
  647. return Combine (new string [] { path1, path2, path3 });
  648. }
  649. public static string Combine (string path1, string path2, string path3, string path4)
  650. {
  651. return Combine (new string [] { path1, path2, path3, path4 });
  652. }
  653. #endif
  654. }
  655. }