Path.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. #if NET_2_0
  48. [ComVisible (true)]
  49. public static class Path {
  50. [Obsolete ("see GetInvalidPathChars and GetInvalidFileNameChars methods.")]
  51. public static readonly char[] InvalidPathChars;
  52. #else
  53. public sealed class Path {
  54. private Path ()
  55. {
  56. }
  57. public static readonly char[] InvalidPathChars;
  58. #endif
  59. public static readonly char AltDirectorySeparatorChar;
  60. public static readonly char DirectorySeparatorChar;
  61. public static readonly char PathSeparator;
  62. internal static readonly string DirectorySeparatorStr;
  63. public static readonly char VolumeSeparatorChar;
  64. private static readonly char[] PathSeparatorChars;
  65. private static readonly bool dirEqualsVolume;
  66. // class methods
  67. public static string ChangeExtension (string path, string extension)
  68. {
  69. if (path == null)
  70. return null;
  71. if (path.IndexOfAny (InvalidPathChars) != -1)
  72. throw new ArgumentException ("Illegal characters in path", "path");
  73. int iExt = findExtension (path);
  74. if (extension == null)
  75. return iExt < 0 ? path : path.Substring (0, iExt);
  76. else if (extension == String.Empty)
  77. return iExt < 0 ? path + '.' : path.Substring (0, iExt + 1);
  78. else if (path.Length != 0) {
  79. if (extension.Length > 0 && extension [0] != '.')
  80. extension = "." + extension;
  81. } else
  82. extension = String.Empty;
  83. if (iExt < 0) {
  84. return path + extension;
  85. } else if (iExt > 0) {
  86. string temp = path.Substring (0, iExt);
  87. return temp + extension;
  88. }
  89. return extension;
  90. }
  91. public static string Combine (string path1, string path2)
  92. {
  93. if (path1 == null)
  94. throw new ArgumentNullException ("path1");
  95. if (path2 == null)
  96. throw new ArgumentNullException ("path2");
  97. if (path1 == String.Empty)
  98. return path2;
  99. if (path2 == String.Empty)
  100. return path1;
  101. if (path1.IndexOfAny (InvalidPathChars) != -1)
  102. throw new ArgumentException ("Illegal characters in path", "path1");
  103. if (path2.IndexOfAny (InvalidPathChars) != -1)
  104. throw new ArgumentException ("Illegal characters in path", "path2");
  105. //TODO???: UNC names
  106. // LAMESPEC: MS says that if path1 is not empty and path2 is a full path
  107. // it should throw ArgumentException
  108. if (IsPathRooted (path2))
  109. return path2;
  110. char p1end = path1 [path1.Length - 1];
  111. if (p1end != DirectorySeparatorChar && p1end != AltDirectorySeparatorChar && p1end != VolumeSeparatorChar)
  112. return path1 + DirectorySeparatorChar + path2;
  113. return path1 + path2;
  114. }
  115. public static string GetDirectoryName (string path)
  116. {
  117. // LAMESPEC: For empty string MS docs say both
  118. // return null AND throw exception. Seems .NET throws.
  119. if (path == String.Empty)
  120. throw new ArgumentException();
  121. if (path == null || GetPathRoot (path) == path)
  122. return null;
  123. CheckArgument.WhitespaceOnly (path);
  124. CheckArgument.PathChars (path);
  125. int nLast = path.LastIndexOfAny (PathSeparatorChars);
  126. if (nLast == 0)
  127. nLast++;
  128. if (nLast > 0) {
  129. string ret = path.Substring (0, nLast);
  130. int l = ret.Length;
  131. if (l >= 2 && ret [l - 1] == VolumeSeparatorChar)
  132. return ret + DirectorySeparatorChar;
  133. else
  134. return ret;
  135. }
  136. return String.Empty;
  137. }
  138. public static string GetExtension (string path)
  139. {
  140. if (path == null)
  141. return null;
  142. if (path.IndexOfAny (InvalidPathChars) != -1)
  143. throw new ArgumentException ("Illegal characters in path", "path");
  144. int iExt = findExtension (path);
  145. if (iExt > -1)
  146. {
  147. if (iExt < path.Length - 1)
  148. return path.Substring (iExt);
  149. }
  150. return string.Empty;
  151. }
  152. public static string GetFileName (string path)
  153. {
  154. if (path == null || path == String.Empty)
  155. return path;
  156. if (path.IndexOfAny (InvalidPathChars) != -1)
  157. throw new ArgumentException ("Illegal characters in path", "path");
  158. int nLast = path.LastIndexOfAny (PathSeparatorChars);
  159. if (nLast >= 0)
  160. return path.Substring (nLast + 1);
  161. return path;
  162. }
  163. public static string GetFileNameWithoutExtension (string path)
  164. {
  165. return ChangeExtension (GetFileName (path), null);
  166. }
  167. public static string GetFullPath (string path)
  168. {
  169. string fullpath = InsecureGetFullPath (path);
  170. if (SecurityManager.SecurityEnabled) {
  171. new FileIOPermission (FileIOPermissionAccess.PathDiscovery, fullpath).Demand ();
  172. }
  173. return fullpath;
  174. }
  175. internal static string WindowsDriveAdjustment (string path)
  176. {
  177. // two special cases to consider when a drive is specified
  178. if (path.Length < 2)
  179. return path;
  180. if ((path [1] != ':') || !Char.IsLetter (path [0]))
  181. return path;
  182. string current = Directory.GetCurrentDirectory ();
  183. // first, only the drive is specified
  184. if (path.Length == 2) {
  185. // then if the current directory is on the same drive
  186. if (current [0] == path [0])
  187. path = current; // we return it
  188. else
  189. path += '\\';
  190. } else if ((path [2] != Path.DirectorySeparatorChar) && (path [2] != Path.AltDirectorySeparatorChar)) {
  191. // second, the drive + a directory is specified *without* a separator between them (e.g. C:dir).
  192. // If the current directory is on the specified drive...
  193. if (current [0] == path [0]) {
  194. // then specified directory is appended to the current drive directory
  195. path = Path.Combine (current, path.Substring (2, path.Length - 2));
  196. } else {
  197. // if not, then just pretend there was a separator (Path.Combine won't work in this case)
  198. path = String.Concat (path.Substring (0, 2), DirectorySeparatorStr, path.Substring (2, path.Length - 2));
  199. }
  200. }
  201. return path;
  202. }
  203. // insecure - do not call directly
  204. internal static string InsecureGetFullPath (string path)
  205. {
  206. if (path == null)
  207. throw new ArgumentNullException ("path");
  208. if (path.Trim ().Length == 0) {
  209. string msg = Locale.GetText ("The specified path is not of a legal form (empty).");
  210. throw new ArgumentException (msg, "path");
  211. }
  212. // adjust for drives, i.e. a special case for windows
  213. if (Environment.IsRunningOnWindows)
  214. path = WindowsDriveAdjustment (path);
  215. // if the supplied path ends with a separator...
  216. char end = path [path.Length - 1];
  217. if (path.Length >= 2 &&
  218. IsDsc (path [0]) &&
  219. IsDsc (path [1])) {
  220. if (path.Length == 2 || path.IndexOf (path [0], 2) < 0)
  221. throw new ArgumentException ("UNC pass should be of the form \\\\server\\share.");
  222. if (path [0] != DirectorySeparatorChar)
  223. path = path.Replace (AltDirectorySeparatorChar, DirectorySeparatorChar);
  224. } else {
  225. if (!IsPathRooted (path))
  226. path = Directory.GetCurrentDirectory () + DirectorySeparatorStr + path;
  227. else if (DirectorySeparatorChar == '\\' &&
  228. path.Length >= 2 &&
  229. IsDsc (path [0]) &&
  230. !IsDsc (path [1])) { // like `\abc\def'
  231. string current = Directory.GetCurrentDirectory ();
  232. if (current [1] == VolumeSeparatorChar)
  233. path = current.Substring (0, 2) + path;
  234. else
  235. path = current.Substring (0, current.IndexOf ('\\', current.IndexOf ("\\\\") + 1));
  236. }
  237. path = CanonicalizePath (path);
  238. }
  239. // if the original ended with a [Alt]DirectorySeparatorChar then ensure the full path also ends with one
  240. if (IsDsc (end) && (path [path.Length - 1] != DirectorySeparatorChar))
  241. path += DirectorySeparatorChar;
  242. return path;
  243. }
  244. static bool IsDsc (char c) {
  245. return c == DirectorySeparatorChar || c == AltDirectorySeparatorChar;
  246. }
  247. public static string GetPathRoot (string path)
  248. {
  249. if (path == null)
  250. return null;
  251. if (path == String.Empty)
  252. throw new ArgumentException ("This specified path is invalid.");
  253. if (!IsPathRooted (path))
  254. return String.Empty;
  255. if (DirectorySeparatorChar == '/') {
  256. // UNIX
  257. return IsDsc (path [0]) ? DirectorySeparatorStr : String.Empty;
  258. } else {
  259. // Windows
  260. int len = 2;
  261. if (path.Length == 1 && IsDsc (path [0]))
  262. return DirectorySeparatorStr;
  263. else if (path.Length < 2)
  264. return String.Empty;
  265. if (IsDsc (path [0]) && IsDsc (path[1])) {
  266. // UNC: \\server or \\server\share
  267. // Get server
  268. while (len < path.Length && !IsDsc (path [len])) len++;
  269. // Get share
  270. if (len < path.Length) {
  271. len++;
  272. while (len < path.Length && !IsDsc (path [len])) len++;
  273. }
  274. return DirectorySeparatorStr +
  275. DirectorySeparatorStr +
  276. path.Substring (2, len - 2).Replace (AltDirectorySeparatorChar, DirectorySeparatorChar);
  277. } else if (IsDsc (path [0])) {
  278. // path starts with '\' or '/'
  279. return DirectorySeparatorStr;
  280. } else if (path[1] == VolumeSeparatorChar) {
  281. // C:\folder
  282. if (path.Length >= 3 && (IsDsc (path [2]))) len++;
  283. } else
  284. return Directory.GetCurrentDirectory ().Substring (0, 2);// + path.Substring (0, len);
  285. return path.Substring (0, len);
  286. }
  287. }
  288. // FIXME: Further limit the assertion when imperative Assert is implemented
  289. [FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
  290. public static string GetTempFileName ()
  291. {
  292. FileStream f = null;
  293. string path;
  294. Random rnd;
  295. int num = 0;
  296. rnd = new Random ();
  297. do {
  298. num = rnd.Next ();
  299. num++;
  300. path = Path.Combine (GetTempPath(), "tmp" + num.ToString("x") + ".tmp");
  301. try {
  302. f = new FileStream (path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.Read,
  303. 8192, false, (FileOptions) 1);
  304. }
  305. catch (SecurityException) {
  306. // avoid an endless loop
  307. throw;
  308. }
  309. catch {
  310. }
  311. } while (f == null);
  312. f.Close();
  313. return path;
  314. }
  315. [EnvironmentPermission (SecurityAction.Demand, Unrestricted = true)]
  316. public static string GetTempPath ()
  317. {
  318. string p = get_temp_path ();
  319. if (p.Length > 0 && p [p.Length - 1] != DirectorySeparatorChar)
  320. return p + DirectorySeparatorChar;
  321. return p;
  322. }
  323. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  324. private static extern string get_temp_path ();
  325. public static bool HasExtension (string path)
  326. {
  327. if (path == null || path.Trim () == String.Empty)
  328. return false;
  329. int pos = findExtension (path);
  330. return 0 <= pos && pos < path.Length - 1;
  331. }
  332. public static bool IsPathRooted (string path)
  333. {
  334. if (path == null || path.Length == 0)
  335. return false;
  336. if (path.IndexOfAny (InvalidPathChars) != -1)
  337. throw new ArgumentException ("Illegal characters in path", "path");
  338. char c = path [0];
  339. return (c == DirectorySeparatorChar ||
  340. c == AltDirectorySeparatorChar ||
  341. (!dirEqualsVolume && path.Length > 1 && path [1] == VolumeSeparatorChar));
  342. }
  343. #if NET_2_0
  344. public static char[] GetInvalidFileNameChars ()
  345. {
  346. // return a new array as we do not want anyone to be able to change the values
  347. if (Environment.IsRunningOnWindows) {
  348. return new char [41] { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  349. '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12',
  350. '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D',
  351. '\x1E', '\x1F', '\x22', '\x3C', '\x3E', '\x7C', ':', '*', '?', '\\', '/' };
  352. } else {
  353. return new char [2] { '\x00', '/' };
  354. }
  355. }
  356. public static char[] GetInvalidPathChars ()
  357. {
  358. // return a new array as we do not want anyone to be able to change the values
  359. if (Environment.IsRunningOnWindows) {
  360. return new char [36] { '\x22', '\x3C', '\x3E', '\x7C', '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  361. '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12',
  362. '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D',
  363. '\x1E', '\x1F' };
  364. } else {
  365. return new char [1] { '\x00' };
  366. }
  367. }
  368. public static string GetRandomFileName ()
  369. {
  370. char[] invalid = GetInvalidFileNameChars ();
  371. // returns a 8.3 filename (total size 12)
  372. StringBuilder sb = new StringBuilder (12);
  373. // using strong crypto but without creating the file
  374. RandomNumberGenerator rng = RandomNumberGenerator.Create ();
  375. byte[] buffer = new byte [16];
  376. while (sb.Length < 12) {
  377. int i = 0;
  378. rng.GetNonZeroBytes (buffer);
  379. while ((i < buffer.Length) && (sb.Length < 12)) {
  380. char c = (char) buffer [i];
  381. if (Array.IndexOf (invalid, c) == -1)
  382. sb.Append (c);
  383. i++;
  384. if (sb.Length == 8)
  385. sb.Append ('.');
  386. }
  387. }
  388. return sb.ToString ();
  389. }
  390. #endif
  391. // private class methods
  392. private static int findExtension (string path)
  393. {
  394. // method should return the index of the path extension
  395. // start or -1 if no valid extension
  396. if (path != null){
  397. int iLastDot = path.LastIndexOf ('.');
  398. int iLastSep = path.LastIndexOfAny ( PathSeparatorChars );
  399. if (iLastDot > iLastSep)
  400. return iLastDot;
  401. }
  402. return -1;
  403. }
  404. static Path ()
  405. {
  406. VolumeSeparatorChar = MonoIO.VolumeSeparatorChar;
  407. DirectorySeparatorChar = MonoIO.DirectorySeparatorChar;
  408. AltDirectorySeparatorChar = MonoIO.AltDirectorySeparatorChar;
  409. PathSeparator = MonoIO.PathSeparator;
  410. #if NET_2_0
  411. // this copy will be modifiable ("by design")
  412. InvalidPathChars = GetInvalidPathChars ();
  413. #else
  414. if (Environment.IsRunningOnWindows) {
  415. InvalidPathChars = new char [15] { '\x00', '\x08', '\x10', '\x11', '\x12', '\x14', '\x15', '\x16',
  416. '\x17', '\x18', '\x19', '\x22', '\x3C', '\x3E', '\x7C' };
  417. } else {
  418. InvalidPathChars = new char [1] { '\x00' };
  419. }
  420. #endif
  421. // internal fields
  422. DirectorySeparatorStr = DirectorySeparatorChar.ToString ();
  423. PathSeparatorChars = new char [] {
  424. DirectorySeparatorChar,
  425. AltDirectorySeparatorChar,
  426. VolumeSeparatorChar
  427. };
  428. dirEqualsVolume = (DirectorySeparatorChar == VolumeSeparatorChar);
  429. }
  430. static bool SameRoot (string root, string path)
  431. {
  432. // compare root - if enough details are available
  433. if ((root.Length < 2) || (path.Length < 2))
  434. return false;
  435. // same volume/drive
  436. if (!root [0].Equals (path [0]))
  437. return false;
  438. // presence if the separator
  439. if (path[1] != Path.VolumeSeparatorChar)
  440. return false;
  441. if ((root.Length > 2) && (path.Length > 2)) {
  442. // but don't directory compare the directory separator
  443. return (IsDsc (root[2]) && IsDsc (path[2]));
  444. }
  445. return true;
  446. }
  447. static string CanonicalizePath (string path)
  448. {
  449. // STEP 1: Check for empty string
  450. if (path == null)
  451. return path;
  452. if (Environment.IsRunningOnWindows)
  453. path = path.Trim ();
  454. if (path.Length == 0)
  455. return path;
  456. // STEP 2: Check to see if this is only a root
  457. string root = Path.GetPathRoot (path);
  458. // it will return '\' for path '\', while it should return 'c:\' or so.
  459. // Note: commenting this out makes the ened for the (target == 1...) check in step 5
  460. //if (root == path) return path;
  461. // STEP 3: split the directories, this gets rid of consecutative "/"'s
  462. string[] dirs = path.Split (Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
  463. // STEP 4: Get rid of directories containing . and ..
  464. int target = 0;
  465. for (int i = 0; i < dirs.Length; i++) {
  466. if (dirs[i] == "." || (i != 0 && dirs[i].Length == 0))
  467. continue;
  468. else if (dirs[i] == "..") {
  469. if (target != 0)
  470. target--;
  471. } else
  472. dirs[target++] = dirs[i];
  473. }
  474. // STEP 5: Combine everything.
  475. if (target == 0 || (target == 1 && dirs[0] == ""))
  476. return root;
  477. else {
  478. string ret = String.Join (DirectorySeparatorStr, dirs, 0, target);
  479. if (Environment.IsRunningOnWindows) {
  480. if (!SameRoot (root, ret))
  481. ret = root + ret;
  482. // In GetFullPath(), it is assured that here never comes UNC. So this must only applied to such path that starts with '\', without drive specification.
  483. if (!IsDsc (path[0]) && SameRoot (root, path)) {
  484. if (ret.Length <= 2 && !ret.EndsWith (DirectorySeparatorStr)) // '\' after "c:"
  485. ret += Path.DirectorySeparatorChar;
  486. return ret;
  487. } else {
  488. string current = Directory.GetCurrentDirectory ();
  489. if (current.Length > 1 && current[1] == Path.VolumeSeparatorChar) {
  490. // DOS local file path
  491. if (ret.Length == 0 || IsDsc (ret[0]))
  492. ret += '\\';
  493. return current.Substring (0, 2) + ret;
  494. } else if (IsDsc (current[current.Length - 1]) && IsDsc (ret[0]))
  495. return current + ret.Substring (1);
  496. else
  497. return current + ret;
  498. }
  499. }
  500. return ret;
  501. }
  502. }
  503. // required for FileIOPermission (and most proibably reusable elsewhere too)
  504. // both path MUST be "full paths"
  505. static internal bool IsPathSubsetOf (string subset, string path)
  506. {
  507. if (subset.Length > path.Length)
  508. return false;
  509. // check that everything up to the last separator match
  510. int slast = subset.LastIndexOfAny (PathSeparatorChars);
  511. if (String.Compare (subset, 0, path, 0, slast) != 0)
  512. return false;
  513. slast++;
  514. // then check if the last segment is identical
  515. int plast = path.IndexOfAny (PathSeparatorChars, slast);
  516. if (plast >= slast) {
  517. return String.Compare (subset, slast, path, slast, path.Length - plast) == 0;
  518. }
  519. if (subset.Length != path.Length)
  520. return false;
  521. return String.Compare (subset, slast, path, slast, subset.Length - slast) == 0;
  522. }
  523. }
  524. }