2 // System.IO.Directory.cs
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)
11 // Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
12 // Copyright (C) 2002 Ximian, Inc.
14 // Created: Monday, August 13, 2001
16 //------------------------------------------------------------------------------
19 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
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:
29 // The above copyright notice and this permission notice shall be
30 // included in all copies or substantial portions of the Software.
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.
41 using System.Collections;
42 using System.Security;
43 using System.Security.Permissions;
46 using System.Security.AccessControl;
61 private Directory () {}
64 public static DirectoryInfo CreateDirectory (string path)
67 throw new ArgumentNullException ("path");
70 throw new ArgumentException ("Path is empty");
72 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
73 throw new ArgumentException ("Path contains invalid chars");
75 if (path.Trim ().Length == 0)
76 throw new ArgumentException ("Only blank characters in path");
79 if (File.Exists(path))
80 throw new IOException ("Cannot create " + path + " because a file with the same name already exists.");
83 // LAMESPEC: with .net 1.0 version this throw NotSupportedException and msdn says so too
84 // but v1.1 throws ArgumentException.
86 throw new ArgumentException ("Only ':' In path");
88 return CreateDirectoriesInternal (path);
91 static DirectoryInfo CreateDirectoriesInternal (string path)
93 if (SecurityManager.SecurityEnabled) {
94 new FileIOPermission (FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, path).Demand ();
97 DirectoryInfo info = new DirectoryInfo (path);
98 if (info.Parent != null && !info.Parent.Exists)
99 info.Parent.Create ();
102 if (!MonoIO.CreateDirectory (path, out error)) {
103 // LAMESPEC: 1.1 and 1.2alpha allow CreateDirectory on a file path.
104 // So CreateDirectory ("/tmp/somefile") will succeed if 'somefile' is
105 // not a directory. However, 1.0 will throw an exception.
106 // We behave like 1.0 here (emulating 1.1-like behavior is just a matter
107 // of comparing error to ERROR_FILE_EXISTS, but it's lame to do:
108 // DirectoryInfo di = Directory.CreateDirectory (something);
109 // and having di.Exists return false afterwards.
110 // I hope we don't break anyone's code, as they should be catching
111 // the exception anyway.
112 if (error != MonoIOError.ERROR_ALREADY_EXISTS &&
113 error != MonoIOError.ERROR_FILE_EXISTS)
114 throw MonoIO.GetException (path, error);
120 public static void Delete (string path)
123 throw new ArgumentNullException ("path");
126 throw new ArgumentException ("Path is empty");
128 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
129 throw new ArgumentException ("Path contains invalid chars");
131 if (path.Trim().Length == 0)
132 throw new ArgumentException ("Only blank characters in path");
135 throw new NotSupportedException ("Only ':' In path");
140 if (MonoIO.ExistsSymlink (path, out error)) {
141 /* RemoveDirectory maps to rmdir()
142 * which fails on symlinks (ENOTDIR)
144 success = MonoIO.DeleteFile (path, out error);
146 success = MonoIO.RemoveDirectory (path,
153 * In io-layer/io.c rmdir returns error_file_not_found if directory does not exists.
154 * So maybe this could be handled somewhere else?
156 if (error == MonoIOError.ERROR_FILE_NOT_FOUND)
157 throw new DirectoryNotFoundException ("Directory '" + path + "' doesnt exists.");
159 throw MonoIO.GetException (path, error);
163 static void RecursiveDelete (string path)
167 foreach (string dir in GetDirectories (path)) {
168 if (MonoIO.ExistsSymlink (dir, out error)) {
169 MonoIO.DeleteFile (dir, out error);
171 RecursiveDelete (dir);
175 foreach (string file in GetFiles (path))
178 Directory.Delete (path);
181 public static void Delete (string path, bool recurse)
183 CheckPathExceptions (path);
185 if (recurse == false){
190 RecursiveDelete (path);
193 public static bool Exists (string path)
201 exists = MonoIO.ExistsDirectory (path, out error);
202 if (error != MonoIOError.ERROR_SUCCESS &&
203 error != MonoIOError.ERROR_PATH_NOT_FOUND &&
204 error != MonoIOError.ERROR_INVALID_HANDLE &&
205 error != MonoIOError.ERROR_ACCESS_DENIED) {
207 // INVALID_HANDLE might happen if the file is moved
208 // while testing for the existence, a kernel issue
209 // according to Larry Ewing.
211 throw MonoIO.GetException (path, error);
217 public static DateTime GetLastAccessTime (string path)
219 return File.GetLastAccessTime (path);
222 public static DateTime GetLastAccessTimeUtc (string path)
224 return GetLastAccessTime (path).ToUniversalTime ();
227 public static DateTime GetLastWriteTime (string path)
229 return File.GetLastWriteTime (path);
232 public static DateTime GetLastWriteTimeUtc (string path)
234 return GetLastWriteTime (path).ToUniversalTime ();
237 public static DateTime GetCreationTime (string path)
239 return File.GetCreationTime (path);
242 public static DateTime GetCreationTimeUtc (string path)
244 return GetCreationTime (path).ToUniversalTime ();
247 public static string GetCurrentDirectory ()
251 string result = MonoIO.GetCurrentDirectory (out error);
252 if (error != MonoIOError.ERROR_SUCCESS)
253 throw MonoIO.GetException (error);
255 if ((result != null) && (result.Length > 0) && SecurityManager.SecurityEnabled) {
256 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, result).Demand ();
261 public static string [] GetDirectories (string path)
263 return GetDirectories (path, "*");
266 public static string [] GetDirectories (string path, string pattern)
268 return GetFileSystemEntries (path, pattern, FileAttributes.Directory, FileAttributes.Directory);
272 public static string [] GetDirectories (string path, string pattern, SearchOption option)
274 if (option == SearchOption.TopDirectoryOnly)
275 return GetDirectories (path, pattern);
276 ArrayList all = new ArrayList ();
277 GetDirectoriesRecurse (path, pattern, all);
278 return (string []) all.ToArray (typeof (string));
281 static void GetDirectoriesRecurse (string path, string pattern, ArrayList all)
283 all.AddRange (GetDirectories (path, pattern));
284 foreach (string dir in GetDirectories (path))
285 GetDirectoriesRecurse (dir, pattern, all);
289 public static string GetDirectoryRoot (string path)
291 return new String(Path.DirectorySeparatorChar,1);
294 public static string [] GetFiles (string path)
296 return GetFiles (path, "*");
299 public static string [] GetFiles (string path, string pattern)
301 return GetFileSystemEntries (path, pattern, FileAttributes.Directory, 0);
305 public static string[] GetFiles (string path, string searchPattern, SearchOption searchOption)
307 if (searchOption == SearchOption.TopDirectoryOnly)
308 return GetFiles (path, searchPattern);
309 ArrayList all = new ArrayList ();
310 GetFilesRecurse (path, searchPattern, all);
311 return (string []) all.ToArray (typeof (string));
314 static void GetFilesRecurse (string path, string pattern, ArrayList all)
316 all.AddRange (GetFiles (path, pattern));
317 foreach (string dir in GetDirectories (path))
318 GetFilesRecurse (dir, pattern, all);
322 public static string [] GetFileSystemEntries (string path)
324 return GetFileSystemEntries (path, "*");
327 public static string [] GetFileSystemEntries (string path, string pattern)
329 return GetFileSystemEntries (path, pattern, 0, 0);
332 public static string[] GetLogicalDrives ()
334 return Environment.GetLogicalDrives ();
337 static bool IsRootDirectory (string path)
340 if (Path.DirectorySeparatorChar == '/' && path == "/")
344 if (Path.DirectorySeparatorChar == '\\')
345 if (path.Length == 3 && path.EndsWith (":\\"))
351 public static DirectoryInfo GetParent (string path)
354 throw new ArgumentNullException ();
355 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
356 throw new ArgumentException ("Path contains invalid characters");
358 throw new ArgumentException ("The Path do not have a valid format");
360 // return null if the path is the root directory
361 if (IsRootDirectory (path))
364 string parent_name = Path.GetDirectoryName (path);
365 if (parent_name == "")
366 parent_name = GetCurrentDirectory();
368 return new DirectoryInfo (parent_name);
371 public static void Move (string src, string dest)
374 throw new ArgumentNullException ("src");
377 throw new ArgumentNullException ("dest");
379 if (src.Trim () == "" || src.IndexOfAny (Path.InvalidPathChars) != -1)
380 throw new ArgumentException ("Invalid source directory name: " + src, "src");
382 if (dest.Trim () == "" || dest.IndexOfAny (Path.InvalidPathChars) != -1)
383 throw new ArgumentException ("Invalid target directory name: " + dest, "dest");
386 throw new IOException ("Source directory cannot be same as a target directory.");
389 throw new IOException (dest + " already exists.");
392 throw new DirectoryNotFoundException (src + " does not exist");
395 if (!MonoIO.MoveFile (src, dest, out error))
396 throw MonoIO.GetException (error);
399 public static void SetCreationTime (string path, DateTime creation_time)
401 File.SetCreationTime (path, creation_time);
404 public static void SetCreationTimeUtc (string path, DateTime creation_time)
406 SetCreationTime (path, creation_time.ToLocalTime ());
409 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
410 public static void SetCurrentDirectory (string path)
413 throw new ArgumentNullException ("path");
414 if (path.Trim () == String.Empty)
415 throw new ArgumentException ("path string must not be an empty string or whitespace string");
420 throw new DirectoryNotFoundException ("Directory \"" +
421 path + "\" not found.");
423 MonoIO.SetCurrentDirectory (path, out error);
424 if (error != MonoIOError.ERROR_SUCCESS)
425 throw MonoIO.GetException (path, error);
428 public static void SetLastAccessTime (string path, DateTime last_access_time)
430 File.SetLastAccessTime (path, last_access_time);
433 public static void SetLastAccessTimeUtc (string path, DateTime last_access_time)
435 SetLastAccessTime (path, last_access_time.ToLocalTime ());
438 public static void SetLastWriteTime (string path, DateTime last_write_time)
440 File.SetLastWriteTime (path, last_write_time);
443 public static void SetLastWriteTimeUtc (string path, DateTime last_write_time)
445 SetLastWriteTime (path, last_write_time.ToLocalTime ());
450 private static void CheckPathExceptions (string path)
453 throw new System.ArgumentNullException("Path is Null");
455 throw new System.ArgumentException("Path is Empty");
456 if (path.Trim().Length == 0)
457 throw new ArgumentException ("Only blank characters in path");
458 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
459 throw new ArgumentException ("Path contains invalid chars");
462 private static string [] GetFileSystemEntries (string path, string pattern, FileAttributes mask, FileAttributes attrs)
464 if (path == null || pattern == null)
465 throw new ArgumentNullException ();
467 if (pattern == String.Empty)
468 return new string [] {};
470 if (path.Trim () == "")
471 throw new ArgumentException ("The Path does not have a valid format");
473 string wild = Path.Combine (path, pattern);
474 string wildpath = Path.GetDirectoryName (wild);
475 if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1)
476 throw new ArgumentException ("Path contains invalid characters");
478 if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1) {
479 if (path.IndexOfAny (SearchPattern.InvalidChars) == -1)
480 throw new ArgumentException ("Path contains invalid characters", "path");
482 throw new ArgumentException ("Pattern contains invalid characters", "pattern");
486 if (!MonoIO.ExistsDirectory (wildpath, out error)) {
487 if (error == MonoIOError.ERROR_SUCCESS) {
488 MonoIOError file_error;
489 if (MonoIO.ExistsFile (wildpath, out file_error)) {
490 return new string [] { wildpath };
494 if (error != MonoIOError.ERROR_PATH_NOT_FOUND)
495 throw MonoIO.GetException (wildpath, error);
497 if (wildpath.IndexOfAny (SearchPattern.WildcardChars) == -1)
498 throw new DirectoryNotFoundException ("Directory '" + wildpath + "' not found.");
500 if (path.IndexOfAny (SearchPattern.WildcardChars) == -1)
501 throw new ArgumentException ("Pattern is invalid", "pattern");
503 throw new ArgumentException ("Path is invalid", "path");
506 string [] result = MonoIO.GetFileSystemEntries (wildpath, pattern, (int) attrs, (int) mask, out error);
508 throw MonoIO.GetException (wildpath, error);
514 [MonoNotSupported ("DirectorySecurity isn't implemented")]
515 public static DirectorySecurity GetAccessControl (string path, AccessControlSections includeSections)
517 throw new PlatformNotSupportedException ();
520 [MonoNotSupported ("DirectorySecurity isn't implemented")]
521 public static DirectorySecurity GetAccessControl (string path)
523 throw new PlatformNotSupportedException ();