Path.cs 25 KB

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