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.Collections.Generic;
43 using System.Security;
44 using System.Security.Permissions;
46 using System.Runtime.InteropServices;
49 using System.Security.AccessControl;
55 public static class Directory
58 public static DirectoryInfo CreateDirectory (string path)
61 throw new ArgumentNullException ("path");
64 throw new ArgumentException ("Path is empty");
66 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
67 throw new ArgumentException ("Path contains invalid chars");
69 if (path.Trim ().Length == 0)
70 throw new ArgumentException ("Only blank characters in path");
72 // after validations but before File.Exists to avoid an oracle
73 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
75 if (File.Exists(path))
76 throw new IOException ("Cannot create " + path + " because a file with the same name already exists.");
78 // LAMESPEC: with .net 1.0 version this throw NotSupportedException and msdn says so too
79 // but v1.1 throws ArgumentException.
80 if (Environment.IsRunningOnWindows && path == ":")
81 throw new ArgumentException ("Only ':' In path");
83 return CreateDirectoriesInternal (path);
87 [MonoLimitation ("DirectorySecurity not implemented")]
88 public static DirectoryInfo CreateDirectory (string path, DirectorySecurity directorySecurity)
90 return(CreateDirectory (path));
94 static DirectoryInfo CreateDirectoriesInternal (string path)
97 if (SecurityManager.SecurityEnabled) {
98 new FileIOPermission (FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, path).Demand ();
101 DirectoryInfo info = new DirectoryInfo (path, true);
102 if (info.Parent != null && !info.Parent.Exists)
103 info.Parent.Create ();
106 if (!MonoIO.CreateDirectory (path, out error)) {
107 // LAMESPEC: 1.1 and 1.2alpha allow CreateDirectory on a file path.
108 // So CreateDirectory ("/tmp/somefile") will succeed if 'somefile' is
109 // not a directory. However, 1.0 will throw an exception.
110 // We behave like 1.0 here (emulating 1.1-like behavior is just a matter
111 // of comparing error to ERROR_FILE_EXISTS, but it's lame to do:
112 // DirectoryInfo di = Directory.CreateDirectory (something);
113 // and having di.Exists return false afterwards.
114 // I hope we don't break anyone's code, as they should be catching
115 // the exception anyway.
116 if (error != MonoIOError.ERROR_ALREADY_EXISTS &&
117 error != MonoIOError.ERROR_FILE_EXISTS)
118 throw MonoIO.GetException (path, error);
124 public static void Delete (string path)
126 Path.Validate (path);
128 if (Environment.IsRunningOnWindows && path == ":")
129 throw new NotSupportedException ("Only ':' In path");
131 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
136 if (MonoIO.ExistsSymlink (path, out error)) {
137 /* RemoveDirectory maps to rmdir()
138 * which fails on symlinks (ENOTDIR)
140 success = MonoIO.DeleteFile (path, out error);
142 success = MonoIO.RemoveDirectory (path, out error);
148 * In io-layer/io.c rmdir returns error_file_not_found if directory does not exists.
149 * So maybe this could be handled somewhere else?
151 if (error == MonoIOError.ERROR_FILE_NOT_FOUND) {
152 if (File.Exists (path))
153 throw new IOException ("Directory does not exist, but a file of the same name exists.");
155 throw new DirectoryNotFoundException ("Directory does not exist.");
157 throw MonoIO.GetException (path, error);
161 static void RecursiveDelete (string path)
165 foreach (string dir in GetDirectories (path)) {
166 if (MonoIO.ExistsSymlink (dir, out error)) {
167 MonoIO.DeleteFile (dir, out error);
169 RecursiveDelete (dir);
173 foreach (string file in GetFiles (path))
176 Directory.Delete (path);
179 public static void Delete (string path, bool recursive)
181 Path.Validate (path);
182 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
185 RecursiveDelete (path);
190 public static bool Exists (string path)
195 // on Moonlight this does not throw but returns false
196 if (!SecurityManager.CheckElevatedPermissions ())
202 exists = MonoIO.ExistsDirectory (path, out error);
203 /* This should not throw exceptions */
207 public static DateTime GetLastAccessTime (string path)
209 return File.GetLastAccessTime (path);
212 public static DateTime GetLastAccessTimeUtc (string path)
214 return GetLastAccessTime (path).ToUniversalTime ();
217 public static DateTime GetLastWriteTime (string path)
219 return File.GetLastWriteTime (path);
222 public static DateTime GetLastWriteTimeUtc (string path)
224 return GetLastWriteTime (path).ToUniversalTime ();
227 public static DateTime GetCreationTime (string path)
229 return File.GetCreationTime (path);
232 public static DateTime GetCreationTimeUtc (string path)
234 return GetCreationTime (path).ToUniversalTime ();
237 public static string GetCurrentDirectory ()
241 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
243 string result = MonoIO.GetCurrentDirectory (out error);
244 if (error != MonoIOError.ERROR_SUCCESS)
245 throw MonoIO.GetException (error);
247 if ((result != null) && (result.Length > 0) && SecurityManager.SecurityEnabled) {
248 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, result).Demand ();
254 public static string [] GetDirectories (string path)
256 return GetDirectories (path, "*");
259 public static string [] GetDirectories (string path, string searchPattern)
261 return GetFileSystemEntries (path, searchPattern, FileAttributes.Directory, FileAttributes.Directory);
265 public static string [] GetDirectories (string path, string searchPattern, SearchOption searchOption)
267 if (searchOption == SearchOption.TopDirectoryOnly)
268 return GetDirectories (path, searchPattern);
269 var all = new List<string> ();
270 GetDirectoriesRecurse (path, searchPattern, all);
271 return all.ToArray ();
274 static void GetDirectoriesRecurse (string path, string searchPattern, List<string> all)
276 all.AddRange (GetDirectories (path, searchPattern));
277 foreach (string dir in GetDirectories (path))
278 GetDirectoriesRecurse (dir, searchPattern, all);
282 public static string GetDirectoryRoot (string path)
284 Path.Validate (path);
285 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
287 // FIXME nice hack but that does not work under windows
288 return new String(Path.DirectorySeparatorChar,1);
291 public static string [] GetFiles (string path)
293 return GetFiles (path, "*");
296 public static string [] GetFiles (string path, string searchPattern)
298 return GetFileSystemEntries (path, searchPattern, FileAttributes.Directory, 0);
302 public static string[] GetFiles (string path, string searchPattern, SearchOption searchOption)
304 if (searchOption == SearchOption.TopDirectoryOnly)
305 return GetFiles (path, searchPattern);
306 var all = new List<string> ();
307 GetFilesRecurse (path, searchPattern, all);
308 return all.ToArray ();
311 static void GetFilesRecurse (string path, string searchPattern, List<string> all)
313 all.AddRange (GetFiles (path, searchPattern));
314 foreach (string dir in GetDirectories (path))
315 GetFilesRecurse (dir, searchPattern, all);
319 public static string [] GetFileSystemEntries (string path)
321 return GetFileSystemEntries (path, "*");
324 public static string [] GetFileSystemEntries (string path, string searchPattern)
326 return GetFileSystemEntries (path, searchPattern, 0, 0);
329 public static string[] GetLogicalDrives ()
331 return Environment.GetLogicalDrives ();
334 static bool IsRootDirectory (string path)
337 if (Path.DirectorySeparatorChar == '/' && path == "/")
341 if (Path.DirectorySeparatorChar == '\\')
342 if (path.Length == 3 && path.EndsWith (":\\"))
348 public static DirectoryInfo GetParent (string path)
350 Path.Validate (path);
352 // return null if the path is the root directory
353 if (IsRootDirectory (path))
356 string parent_name = Path.GetDirectoryName (path);
357 if (parent_name.Length == 0)
358 parent_name = GetCurrentDirectory();
360 return new DirectoryInfo (parent_name);
363 public static void Move (string sourceDirName, string destDirName)
365 if (sourceDirName == null)
366 throw new ArgumentNullException ("sourceDirName");
368 if (destDirName == null)
369 throw new ArgumentNullException ("destDirName");
371 if (sourceDirName.Trim ().Length == 0 || sourceDirName.IndexOfAny (Path.InvalidPathChars) != -1)
372 throw new ArgumentException ("Invalid source directory name: " + sourceDirName, "sourceDirName");
374 if (destDirName.Trim ().Length == 0 || destDirName.IndexOfAny (Path.InvalidPathChars) != -1)
375 throw new ArgumentException ("Invalid target directory name: " + destDirName, "destDirName");
377 if (sourceDirName == destDirName)
378 throw new IOException ("Source and destination path must be different.");
380 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
382 if (Exists (destDirName))
383 throw new IOException (destDirName + " already exists.");
385 if (!Exists (sourceDirName) && !File.Exists (sourceDirName))
386 throw new DirectoryNotFoundException (sourceDirName + " does not exist");
389 if (!MonoIO.MoveFile (sourceDirName, destDirName, out error))
390 throw MonoIO.GetException (error);
394 public static void SetAccessControl (string path, DirectorySecurity directorySecurity)
396 if (null == directorySecurity)
397 throw new ArgumentNullException ("directorySecurity");
399 directorySecurity.PersistModifications (path);
403 public static void SetCreationTime (string path, DateTime creationTime)
405 File.SetCreationTime (path, creationTime);
408 public static void SetCreationTimeUtc (string path, DateTime creationTimeUtc)
410 SetCreationTime (path, creationTimeUtc.ToLocalTime ());
413 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
414 public static void SetCurrentDirectory (string path)
417 throw new ArgumentNullException ("path");
418 if (path.Trim ().Length == 0)
419 throw new ArgumentException ("path string must not be an empty string or whitespace string");
424 throw new DirectoryNotFoundException ("Directory \"" +
425 path + "\" not found.");
427 MonoIO.SetCurrentDirectory (path, out error);
428 if (error != MonoIOError.ERROR_SUCCESS)
429 throw MonoIO.GetException (path, error);
432 public static void SetLastAccessTime (string path, DateTime lastAccessTime)
434 File.SetLastAccessTime (path, lastAccessTime);
437 public static void SetLastAccessTimeUtc (string path, DateTime lastAccessTimeUtc)
439 SetLastAccessTime (path, lastAccessTimeUtc.ToLocalTime ());
442 public static void SetLastWriteTime (string path, DateTime lastWriteTime)
444 File.SetLastWriteTime (path, lastWriteTime);
447 public static void SetLastWriteTimeUtc (string path, DateTime lastWriteTimeUtc)
449 SetLastWriteTime (path, lastWriteTimeUtc.ToLocalTime ());
454 // Does the common validation, searchPattern has already been checked for not-null
455 static string ValidateDirectoryListing (string path, string searchPattern, out bool stop)
457 Path.Validate (path);
459 string wild = Path.Combine (path, searchPattern);
460 string wildpath = Path.GetDirectoryName (wild);
461 if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1)
462 throw new ArgumentException ("Pattern contains invalid characters", "pattern");
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 throw new IOException ("The directory name is invalid.");
472 if (error != MonoIOError.ERROR_PATH_NOT_FOUND)
473 throw MonoIO.GetException (wildpath, error);
475 if (wildpath.IndexOfAny (SearchPattern.WildcardChars) == -1)
476 throw new DirectoryNotFoundException ("Directory '" + wildpath + "' not found.");
478 if (path.IndexOfAny (SearchPattern.WildcardChars) == -1)
479 throw new ArgumentException ("Pattern is invalid", "searchPattern");
481 throw new ArgumentException ("Path is invalid", "path");
488 private static string [] GetFileSystemEntries (string path, string searchPattern, FileAttributes mask, FileAttributes attrs)
490 if (searchPattern == null)
491 throw new ArgumentNullException ("searchPattern");
492 if (searchPattern.Length == 0)
493 return new string [] {};
495 string path_with_pattern = ValidateDirectoryListing (path, searchPattern, out stop);
497 return new string [] { path_with_pattern };
500 string [] result = MonoIO.GetFileSystemEntries (path, path_with_pattern, (int) attrs, (int) mask, out error);
502 throw MonoIO.GetException (Path.GetDirectoryName (Path.Combine (path, searchPattern)), error);
507 #if NET_4_0 || MOONLIGHT || MOBILE
508 public static string[] GetFileSystemEntries (string path, string searchPattern, SearchOption searchOption)
510 // Take the simple way home:
511 return new List<string> (EnumerateFileSystemEntries (path, searchPattern, searchOption)).ToArray ();
514 static void EnumerateCheck (string path, string searchPattern, SearchOption searchOption)
516 if (searchPattern == null)
517 throw new ArgumentNullException ("searchPattern");
519 if (searchPattern.Length == 0)
522 if (searchOption != SearchOption.TopDirectoryOnly && searchOption != SearchOption.AllDirectories)
523 throw new ArgumentOutOfRangeException ("searchoption");
525 Path.Validate (path);
526 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
529 internal static IEnumerable<string> EnumerateKind (string path, string searchPattern, SearchOption searchOption, FileAttributes kind)
531 if (searchPattern.Length == 0)
535 string path_with_pattern = ValidateDirectoryListing (path, searchPattern, out stop);
537 yield return path_with_pattern;
543 FileAttributes rattr;
544 bool subdirs = searchOption == SearchOption.AllDirectories;
546 string s = MonoIO.FindFirst (path, path_with_pattern, out rattr, out error, out handle);
550 throw MonoIO.GetException (Path.GetDirectoryName (Path.Combine (path, searchPattern)), (MonoIOError) error);
554 // Convert any file specific flag to FileAttributes.Normal which is used as include files flag
556 if (((rattr & FileAttributes.Directory) == 0) && rattr != 0)
557 rattr |= FileAttributes.Normal;
560 if (((rattr & FileAttributes.ReparsePoint) == 0) && ((rattr & kind) != 0))
564 if (((rattr & FileAttributes.Directory) != 0) && subdirs) {
565 foreach (string child in EnumerateKind (s, searchPattern, searchOption, kind))
574 if ((rattr & FileAttributes.ReparsePoint) != 0)
577 if ((rattr & kind) != 0)
579 } while ((s = MonoIO.FindNext (handle, out rattr, out error)) != null);
581 MonoIO.FindClose (handle);
585 public static IEnumerable<string> EnumerateDirectories (string path, string searchPattern, SearchOption searchOption)
587 EnumerateCheck (path, searchPattern, searchOption);
588 return EnumerateKind (path, searchPattern, searchOption, FileAttributes.Directory);
591 public static IEnumerable<string> EnumerateDirectories (string path, string searchPattern)
593 EnumerateCheck (path, searchPattern, SearchOption.TopDirectoryOnly);
594 return EnumerateKind (path, searchPattern, SearchOption.TopDirectoryOnly, FileAttributes.Directory);
597 public static IEnumerable<string> EnumerateDirectories (string path)
599 Path.Validate (path); // no need for EnumerateCheck since we supply valid arguments
600 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
601 return EnumerateKind (path, "*", SearchOption.TopDirectoryOnly, FileAttributes.Directory);
604 public static IEnumerable<string> EnumerateFiles (string path, string searchPattern, SearchOption searchOption)
606 EnumerateCheck (path, searchPattern, searchOption);
607 return EnumerateKind (path, searchPattern, searchOption, FileAttributes.Normal);
610 public static IEnumerable<string> EnumerateFiles (string path, string searchPattern)
612 EnumerateCheck (path, searchPattern, SearchOption.TopDirectoryOnly);
613 return EnumerateKind (path, searchPattern, SearchOption.TopDirectoryOnly, FileAttributes.Normal);
616 public static IEnumerable<string> EnumerateFiles (string path)
618 Path.Validate (path); // no need for EnumerateCheck since we supply valid arguments
619 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
620 return EnumerateKind (path, "*", SearchOption.TopDirectoryOnly, FileAttributes.Normal);
623 public static IEnumerable<string> EnumerateFileSystemEntries (string path, string searchPattern, SearchOption searchOption)
625 EnumerateCheck (path, searchPattern, searchOption);
626 return EnumerateKind (path, searchPattern, searchOption, FileAttributes.Normal | FileAttributes.Directory);
629 public static IEnumerable<string> EnumerateFileSystemEntries (string path, string searchPattern)
631 EnumerateCheck (path, searchPattern, SearchOption.TopDirectoryOnly);
632 return EnumerateKind (path, searchPattern, SearchOption.TopDirectoryOnly, FileAttributes.Normal | FileAttributes.Directory);
635 public static IEnumerable<string> EnumerateFileSystemEntries (string path)
637 Path.Validate (path); // no need for EnumerateCheck since we supply valid arguments
638 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
639 return EnumerateKind (path, "*", SearchOption.TopDirectoryOnly, FileAttributes.Normal | FileAttributes.Directory);
645 public static DirectorySecurity GetAccessControl (string path, AccessControlSections includeSections)
647 return new DirectorySecurity (path, includeSections);
650 public static DirectorySecurity GetAccessControl (string path)
652 // AccessControlSections.Audit requires special permissions.
653 return GetAccessControl (path,
654 AccessControlSections.Owner |
655 AccessControlSections.Group |
656 AccessControlSections.Access);