* Directory.cs: Renamed Move arguments to match MS. Allow Move to be
[mono.git] / mcs / class / corlib / System.IO / Directory.cs
1 // 
2 // System.IO.Directory.cs 
3 //
4 // Authors:
5 //   Jim Richardson  (develop@wtfo-guru.com)
6 //   Miguel de Icaza (miguel@ximian.com)
7 //   Dan Lewis       (dihlewis@yahoo.co.uk)
8 //   Eduardo Garcia  (kiwnix@yahoo.es)
9 //   Ville Palo      (vi64pa@kolumbus.fi)
10 //
11 // Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
12 // Copyright (C) 2002 Ximian, Inc.
13 // 
14 // Created:        Monday, August 13, 2001 
15 //
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
41 using System.Collections;
42 using System.Security;
43 using System.Security.Permissions;
44 using System.Text;
45 #if NET_2_0
46 using System.Security.AccessControl;
47 using System.Runtime.InteropServices;
48 #endif
49
50 namespace System.IO
51 {
52 #if NET_2_0
53         [ComVisible (true)]
54 #endif
55         public
56 #if NET_2_0
57         static
58 #else
59         sealed
60 #endif
61         class Directory
62         {
63
64 #if !NET_2_0
65                 private Directory () {}
66 #endif
67                 
68                 public static DirectoryInfo CreateDirectory (string path)
69                 {
70                         if (path == null)
71                                 throw new ArgumentNullException ("path");
72                         
73                         if (path == "")
74                                 throw new ArgumentException ("Path is empty");
75                         
76                         if (path.IndexOfAny (Path.InvalidPathChars) != -1)
77                                 throw new ArgumentException ("Path contains invalid chars");
78
79                         if (path.Trim ().Length == 0)
80                                 throw new ArgumentException ("Only blank characters in path");
81
82 #if NET_2_0
83                         if (File.Exists(path))
84                                 throw new IOException ("Cannot create " + path + " because a file with the same name already exists.");
85 #endif
86                         
87                         // LAMESPEC: with .net 1.0 version this throw NotSupportedException and msdn says so too
88                         // but v1.1 throws ArgumentException.
89                         if (path == ":")
90                                 throw new ArgumentException ("Only ':' In path");
91                         
92                         return CreateDirectoriesInternal (path);
93                 }
94
95 #if NET_2_0
96                 [MonoTODO ("DirectorySecurity not implemented")]
97                 public static DirectoryInfo CreateDirectory (string path, DirectorySecurity directorySecurity)
98                 {
99                         return(CreateDirectory (path));
100                 }
101 #endif
102
103                 static DirectoryInfo CreateDirectoriesInternal (string path)
104                 {
105                         if (SecurityManager.SecurityEnabled) {
106                                 new FileIOPermission (FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, path).Demand ();
107                         }
108
109                         DirectoryInfo info = new DirectoryInfo (path);
110                         if (info.Parent != null && !info.Parent.Exists)
111                                  info.Parent.Create ();
112
113                         MonoIOError error;
114                         if (!MonoIO.CreateDirectory (path, out error)) {
115                                 // LAMESPEC: 1.1 and 1.2alpha allow CreateDirectory on a file path.
116                                 // So CreateDirectory ("/tmp/somefile") will succeed if 'somefile' is
117                                 // not a directory. However, 1.0 will throw an exception.
118                                 // We behave like 1.0 here (emulating 1.1-like behavior is just a matter
119                                 // of comparing error to ERROR_FILE_EXISTS, but it's lame to do:
120                                 //    DirectoryInfo di = Directory.CreateDirectory (something);
121                                 // and having di.Exists return false afterwards.
122                                 // I hope we don't break anyone's code, as they should be catching
123                                 // the exception anyway.
124                                 if (error != MonoIOError.ERROR_ALREADY_EXISTS &&
125                                     error != MonoIOError.ERROR_FILE_EXISTS)
126                                         throw MonoIO.GetException (path, error);
127                         }
128
129                         return info;
130                 }
131                 
132                 public static void Delete (string path)
133                 {
134                         if (path == null)
135                                 throw new ArgumentNullException ("path");
136                         
137                         if (path == "")
138                                 throw new ArgumentException ("Path is empty");
139                         
140                         if (path.IndexOfAny (Path.InvalidPathChars) != -1)
141                                 throw new ArgumentException ("Path contains invalid chars");
142
143                         if (path.Trim().Length == 0)
144                                 throw new ArgumentException ("Only blank characters in path");
145
146                         if (path == ":")
147                                 throw new NotSupportedException ("Only ':' In path");
148
149                         MonoIOError error;
150                         bool success;
151                         
152                         if (MonoIO.ExistsSymlink (path, out error)) {
153                                 /* RemoveDirectory maps to rmdir()
154                                  * which fails on symlinks (ENOTDIR)
155                                  */
156                                 success = MonoIO.DeleteFile (path, out error);
157                         } else {
158                                 success = MonoIO.RemoveDirectory (path, out error);
159                         }
160                         
161                         if (!success) {
162                                 /*
163                                  * FIXME:
164                                  * In io-layer/io.c rmdir returns error_file_not_found if directory does not exists.
165                                  * So maybe this could be handled somewhere else?
166                                  */
167                                 if (error == MonoIOError.ERROR_FILE_NOT_FOUND) 
168                                         throw new DirectoryNotFoundException ("Directory '" + path + "' does not exist");
169                                 else
170                                         throw MonoIO.GetException (path, error);
171                         }
172                 }
173
174                 static void RecursiveDelete (string path)
175                 {
176                         MonoIOError error;
177                         
178                         foreach (string dir in GetDirectories (path)) {
179                                 if (MonoIO.ExistsSymlink (dir, out error)) {
180                                         MonoIO.DeleteFile (dir, out error);
181                                 } else {
182                                         RecursiveDelete (dir);
183                                 }
184                         }
185
186                         foreach (string file in GetFiles (path))
187                                 File.Delete (file);
188
189                         Directory.Delete (path);
190                 }
191                 
192                 public static void Delete (string path, bool recurse)
193                 {
194                         CheckPathExceptions (path);
195                         
196                         if (recurse == false){
197                                 Delete (path);
198                                 return;
199                         }
200
201                         RecursiveDelete (path);
202                 }
203
204                 public static bool Exists (string path)
205                 {
206                         if (path == null)
207                                 return false;
208                                 
209                         MonoIOError error;
210                         bool exists;
211                         
212                         exists = MonoIO.ExistsDirectory (path, out error);
213                         if (error != MonoIOError.ERROR_SUCCESS &&
214                             error != MonoIOError.ERROR_PATH_NOT_FOUND &&
215                             error != MonoIOError.ERROR_INVALID_HANDLE &&
216                             error != MonoIOError.ERROR_ACCESS_DENIED) {
217
218                                 // INVALID_HANDLE might happen if the file is moved
219                                 // while testing for the existence, a kernel issue
220                                 // according to Larry Ewing.
221                                 
222                                 throw MonoIO.GetException (path, error);
223                         }
224
225                         return(exists);
226                 }
227
228                 public static DateTime GetLastAccessTime (string path)
229                 {
230                         return File.GetLastAccessTime (path);
231                 }
232
233                 public static DateTime GetLastAccessTimeUtc (string path)
234                 {
235                         return GetLastAccessTime (path).ToUniversalTime ();
236                 }
237
238                 public static DateTime GetLastWriteTime (string path)
239                 {
240                         return File.GetLastWriteTime (path);
241                 }
242                 
243                 public static DateTime GetLastWriteTimeUtc (string path)
244                 {
245                         return GetLastWriteTime (path).ToUniversalTime ();
246                 }
247
248                 public static DateTime GetCreationTime (string path)
249                 {
250                         return File.GetCreationTime (path);
251                 }
252
253                 public static DateTime GetCreationTimeUtc (string path)
254                 {
255                         return GetCreationTime (path).ToUniversalTime ();
256                 }
257
258                 public static string GetCurrentDirectory ()
259                 {
260                         MonoIOError error;
261                                 
262                         string result = MonoIO.GetCurrentDirectory (out error);
263                         if (error != MonoIOError.ERROR_SUCCESS)
264                                 throw MonoIO.GetException (error);
265
266                         if ((result != null) && (result.Length > 0) && SecurityManager.SecurityEnabled) {
267                                 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, result).Demand ();
268                         }
269                         return result;
270                 }
271                 
272                 public static string [] GetDirectories (string path)
273                 {
274                         return GetDirectories (path, "*");
275                 }
276                 
277                 public static string [] GetDirectories (string path, string pattern)
278                 {
279                         return GetFileSystemEntries (path, pattern, FileAttributes.Directory, FileAttributes.Directory);
280                 }
281                 
282 #if NET_2_0
283                 public static string [] GetDirectories (string path, string pattern, SearchOption option)
284                 {
285                         if (option == SearchOption.TopDirectoryOnly)
286                                 return GetDirectories (path, pattern);
287                         ArrayList all = new ArrayList ();
288                         GetDirectoriesRecurse (path, pattern, all);
289                         return (string []) all.ToArray (typeof (string));
290                 }
291                 
292                 static void GetDirectoriesRecurse (string path, string pattern, ArrayList all)
293                 {
294                         all.AddRange (GetDirectories (path, pattern));
295                         foreach (string dir in GetDirectories (path))
296                                 GetDirectoriesRecurse (dir, pattern, all);
297                 }
298 #endif
299
300                 public static string GetDirectoryRoot (string path)
301                 {
302                         return new String(Path.DirectorySeparatorChar,1);
303                 }
304                 
305                 public static string [] GetFiles (string path)
306                 {
307                         return GetFiles (path, "*");
308                 }
309                 
310                 public static string [] GetFiles (string path, string pattern)
311                 {
312                         return GetFileSystemEntries (path, pattern, FileAttributes.Directory, 0);
313                 }
314
315 #if NET_2_0
316                 public static string[] GetFiles (string path, string searchPattern, SearchOption searchOption)
317                 {
318                         if (searchOption == SearchOption.TopDirectoryOnly)
319                                 return GetFiles (path, searchPattern);
320                         ArrayList all = new ArrayList ();
321                         GetFilesRecurse (path, searchPattern, all);
322                         return (string []) all.ToArray (typeof (string));
323                 }
324                 
325                 static void GetFilesRecurse (string path, string pattern, ArrayList all)
326                 {
327                         all.AddRange (GetFiles (path, pattern));
328                         foreach (string dir in GetDirectories (path))
329                                 GetFilesRecurse (dir, pattern, all);
330                 }
331 #endif
332
333                 public static string [] GetFileSystemEntries (string path)
334                 {
335                         return GetFileSystemEntries (path, "*");
336                 }
337
338                 public static string [] GetFileSystemEntries (string path, string pattern)
339                 {
340                         return GetFileSystemEntries (path, pattern, 0, 0);
341                 }
342                 
343                 public static string[] GetLogicalDrives ()
344                 { 
345                         return Environment.GetLogicalDrives ();
346                 }
347
348                 static bool IsRootDirectory (string path)
349                 {
350                         // Unix
351                         if (Path.DirectorySeparatorChar == '/' && path == "/")
352                                 return true;
353
354                         // Windows
355                         if (Path.DirectorySeparatorChar == '\\')
356                                 if (path.Length == 3 && path.EndsWith (":\\"))
357                                         return true;
358
359                         return false;
360                 }
361
362                 public static DirectoryInfo GetParent (string path)
363                 {
364                         if (path == null)
365                                 throw new ArgumentNullException ();
366                         if (path.IndexOfAny (Path.InvalidPathChars) != -1)
367                                 throw new ArgumentException ("Path contains invalid characters");
368                         if (path == "")
369                                 throw new ArgumentException ("The Path do not have a valid format");
370
371                         // return null if the path is the root directory
372                         if (IsRootDirectory (path))
373                                 return null;
374
375                         string parent_name = Path.GetDirectoryName (path);
376                         if (parent_name == "")
377                                 parent_name = GetCurrentDirectory();
378
379                         return new DirectoryInfo (parent_name);
380                 }
381
382                 public static void Move (string sourceDirName, string destDirName)
383                 {
384                         if (sourceDirName == null)
385                                 throw new ArgumentNullException ("sourceDirName");
386
387                         if (destDirName == null)
388                                 throw new ArgumentNullException ("destDirName");
389
390                         if (sourceDirName.Trim () == "" || sourceDirName.IndexOfAny (Path.InvalidPathChars) != -1)
391                                 throw new ArgumentException ("Invalid source directory name: " + sourceDirName, "sourceDirName");
392
393                         if (destDirName.Trim () == "" || destDirName.IndexOfAny (Path.InvalidPathChars) != -1)
394                                 throw new ArgumentException ("Invalid target directory name: " + destDirName, "destDirName");
395
396                         if (sourceDirName == destDirName)
397                                 throw new IOException ("Source and destination path must be different.");
398
399                         if (Exists (destDirName))
400                                 throw new IOException (destDirName + " already exists.");
401
402                         if (!Exists (sourceDirName) && !File.Exists (sourceDirName))
403                                 throw new DirectoryNotFoundException (sourceDirName + " does not exist");
404
405                         MonoIOError error;
406                         if (!MonoIO.MoveFile (sourceDirName, destDirName, out error))
407                                 throw MonoIO.GetException (error);
408                 }
409
410 #if NET_2_0
411                 public static void SetAccessControl (string path, DirectorySecurity directorySecurity)
412                 {
413                         throw new NotImplementedException ();
414                 }
415 #endif
416
417                 public static void SetCreationTime (string path, DateTime creation_time)
418                 {
419                         File.SetCreationTime (path, creation_time);
420                 }
421
422                 public static void SetCreationTimeUtc (string path, DateTime creation_time)
423                 {
424                         SetCreationTime (path, creation_time.ToLocalTime ());
425                 }
426
427                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
428                 public static void SetCurrentDirectory (string path)
429                 {
430                         if (path == null)
431                                 throw new ArgumentNullException ("path");
432                         if (path.Trim () == String.Empty)
433                                 throw new ArgumentException ("path string must not be an empty string or whitespace string");
434
435                         MonoIOError error;
436                                 
437                         if (!Exists (path))
438                                 throw new DirectoryNotFoundException ("Directory \"" +
439                                                                         path + "\" not found.");
440
441                         MonoIO.SetCurrentDirectory (path, out error);
442                         if (error != MonoIOError.ERROR_SUCCESS)
443                                 throw MonoIO.GetException (path, error);
444                 }
445
446                 public static void SetLastAccessTime (string path, DateTime last_access_time)
447                 {
448                         File.SetLastAccessTime (path, last_access_time);
449                 }
450
451                 public static void SetLastAccessTimeUtc (string path, DateTime last_access_time)
452                 {
453                         SetLastAccessTime (path, last_access_time.ToLocalTime ());
454                 }
455
456                 public static void SetLastWriteTime (string path, DateTime last_write_time)
457                 {
458                         File.SetLastWriteTime (path, last_write_time);
459                 }
460
461                 public static void SetLastWriteTimeUtc (string path, DateTime last_write_time)
462                 {
463                         SetLastWriteTime (path, last_write_time.ToLocalTime ());
464                 }
465
466                 // private
467                 
468                 private static void CheckPathExceptions (string path)
469                 {
470                         if (path == null)
471                                 throw new System.ArgumentNullException("Path is Null");
472                         if (path == "")
473                                 throw new System.ArgumentException("Path is Empty");
474                         if (path.Trim().Length == 0)
475                                 throw new ArgumentException ("Only blank characters in path");
476                         if (path.IndexOfAny (Path.InvalidPathChars) != -1)
477                                 throw new ArgumentException ("Path contains invalid chars");
478                 }
479
480                 private static string [] GetFileSystemEntries (string path, string pattern, FileAttributes mask, FileAttributes attrs)
481                 {
482                         if (path == null || pattern == null)
483                                 throw new ArgumentNullException ();
484
485                         if (pattern == String.Empty)
486                                 return new string [] {};
487                         
488                         if (path.Trim () == "")
489                                 throw new ArgumentException ("The Path does not have a valid format");
490
491                         string wild = Path.Combine (path, pattern);
492                         string wildpath = Path.GetDirectoryName (wild);
493                         if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1)
494                                 throw new ArgumentException ("Path contains invalid characters");
495
496                         if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1) {
497                                 if (path.IndexOfAny (SearchPattern.InvalidChars) == -1)
498                                         throw new ArgumentException ("Path contains invalid characters", "path");
499
500                                 throw new ArgumentException ("Pattern contains invalid characters", "pattern");
501                         }
502
503                         MonoIOError error;
504                         if (!MonoIO.ExistsDirectory (wildpath, out error)) {
505                                 if (error == MonoIOError.ERROR_SUCCESS) {
506                                         MonoIOError file_error;
507                                         if (MonoIO.ExistsFile (wildpath, out file_error)) {
508                                                 return new string [] { wildpath };
509                                         }
510                                 }
511
512                                 if (error != MonoIOError.ERROR_PATH_NOT_FOUND)
513                                         throw MonoIO.GetException (wildpath, error);
514
515                                 if (wildpath.IndexOfAny (SearchPattern.WildcardChars) == -1)
516                                         throw new DirectoryNotFoundException ("Directory '" + wildpath + "' not found.");
517
518                                 if (path.IndexOfAny (SearchPattern.WildcardChars) == -1)
519                                         throw new ArgumentException ("Pattern is invalid", "pattern");
520
521                                 throw new ArgumentException ("Path is invalid", "path");
522                         }
523
524                         string path_with_pattern = Path.Combine (wildpath, pattern);
525                         string [] result = MonoIO.GetFileSystemEntries (path, path_with_pattern, (int) attrs, (int) mask, out error);
526                         if (error != 0)
527                                 throw MonoIO.GetException (wildpath, error);
528                         
529                         return result;
530                 }
531
532 #if NET_2_0
533                 [MonoNotSupported ("DirectorySecurity isn't implemented")]
534                 public static DirectorySecurity GetAccessControl (string path, AccessControlSections includeSections)
535                 {
536                         throw new PlatformNotSupportedException ();
537                 }
538
539                 [MonoNotSupported ("DirectorySecurity isn't implemented")]
540                 public static DirectorySecurity GetAccessControl (string path)
541                 {
542                         throw new PlatformNotSupportedException ();
543                 }
544 #endif
545         }
546 }