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