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