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;
58 private Directory () {}
61 public static DirectoryInfo CreateDirectory (string path)
64 throw new ArgumentNullException ("path");
67 throw new ArgumentException ("Path is empty");
69 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
70 throw new ArgumentException ("Path contains invalid chars");
72 if (path.Trim ().Length == 0)
73 throw new ArgumentException ("Only blank characters in path");
76 if (File.Exists(path))
77 throw new IOException ("Cannot create " + path + " because a file with the same name already exists.");
80 // LAMESPEC: with .net 1.0 version this throw NotSupportedException and msdn says so too
81 // but v1.1 throws ArgumentException.
83 throw new ArgumentException ("Only ':' In path");
85 return CreateDirectoriesInternal (path);
88 static DirectoryInfo CreateDirectoriesInternal (string path)
90 if (SecurityManager.SecurityEnabled) {
91 new FileIOPermission (FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, path).Demand ();
94 DirectoryInfo info = new DirectoryInfo (path);
95 if (info.Parent != null && !info.Parent.Exists)
96 info.Parent.Create ();
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);
117 public static void Delete (string path)
120 throw new ArgumentNullException ("path");
123 throw new ArgumentException ("Path is empty");
125 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
126 throw new ArgumentException ("Path contains invalid chars");
128 if (path.Trim().Length == 0)
129 throw new ArgumentException ("Only blank characters in path");
132 throw new NotSupportedException ("Only ':' In path");
136 if (!MonoIO.RemoveDirectory (path, out error)) {
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?
142 if (error == MonoIOError.ERROR_FILE_NOT_FOUND)
143 throw new DirectoryNotFoundException ("Directory '" + path + "' doesnt exists.");
145 throw MonoIO.GetException (path, error);
149 static void RecursiveDelete (string path)
151 foreach (string dir in GetDirectories (path))
152 RecursiveDelete (dir);
154 foreach (string file in GetFiles (path))
157 Directory.Delete (path);
160 public static void Delete (string path, bool recurse)
162 CheckPathExceptions (path);
164 if (recurse == false){
169 RecursiveDelete (path);
172 public static bool Exists (string path)
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) {
186 // INVALID_HANDLE might happen if the file is moved
187 // while testing for the existence, a kernel issue
188 // according to Larry Ewing.
190 throw MonoIO.GetException (path, error);
196 public static DateTime GetLastAccessTime (string path)
198 return File.GetLastAccessTime (path);
201 public static DateTime GetLastAccessTimeUtc (string path)
203 return GetLastAccessTime (path).ToUniversalTime ();
206 public static DateTime GetLastWriteTime (string path)
208 return File.GetLastWriteTime (path);
211 public static DateTime GetLastWriteTimeUtc (string path)
213 return GetLastWriteTime (path).ToUniversalTime ();
216 public static DateTime GetCreationTime (string path)
218 return File.GetCreationTime (path);
221 public static DateTime GetCreationTimeUtc (string path)
223 return GetCreationTime (path).ToUniversalTime ();
226 public static string GetCurrentDirectory ()
230 string result = MonoIO.GetCurrentDirectory (out error);
231 if (error != MonoIOError.ERROR_SUCCESS)
232 throw MonoIO.GetException (error);
234 if ((result != null) && (result.Length > 0) && SecurityManager.SecurityEnabled) {
235 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, result).Demand ();
240 public static string [] GetDirectories (string path)
242 return GetDirectories (path, "*");
245 public static string [] GetDirectories (string path, string pattern)
247 return GetFileSystemEntries (path, pattern, FileAttributes.Directory, FileAttributes.Directory);
251 public static string [] GetDirectories (string path, string pattern, SearchOption option)
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));
260 static void GetDirectoriesRecurse (string path, string pattern, ArrayList all)
262 all.AddRange (GetDirectories (path, pattern));
263 foreach (string dir in GetDirectories (path))
264 GetDirectoriesRecurse (dir, pattern, all);
268 public static string GetDirectoryRoot (string path)
270 return new String(Path.DirectorySeparatorChar,1);
273 public static string [] GetFiles (string path)
275 return GetFiles (path, "*");
278 public static string [] GetFiles (string path, string pattern)
280 return GetFileSystemEntries (path, pattern, FileAttributes.Directory, 0);
284 public static string[] GetFiles (string path, string searchPattern, SearchOption searchOption)
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));
293 static void GetFilesRecurse (string path, string pattern, ArrayList all)
295 all.AddRange (GetFiles (path, pattern));
296 foreach (string dir in GetDirectories (path))
297 GetFilesRecurse (dir, pattern, all);
301 public static string [] GetFileSystemEntries (string path)
303 return GetFileSystemEntries (path, "*");
306 public static string [] GetFileSystemEntries (string path, string pattern)
308 return GetFileSystemEntries (path, pattern, 0, 0);
311 public static string[] GetLogicalDrives ()
313 return Environment.GetLogicalDrives ();
316 static bool IsRootDirectory (string path)
319 if (Path.DirectorySeparatorChar == '/' && path == "/")
323 if (Path.DirectorySeparatorChar == '\\')
324 if (path.Length == 3 && path.EndsWith (":\\"))
330 public static DirectoryInfo GetParent (string path)
333 throw new ArgumentNullException ();
334 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
335 throw new ArgumentException ("Path contains invalid characters");
337 throw new ArgumentException ("The Path do not have a valid format");
339 // return null if the path is the root directory
340 if (IsRootDirectory (path))
343 string parent_name = Path.GetDirectoryName (path);
344 if (parent_name == "")
345 parent_name = GetCurrentDirectory();
347 return new DirectoryInfo (parent_name);
350 public static void Move (string src, string dest)
353 throw new ArgumentNullException ("src");
356 throw new ArgumentNullException ("dest");
358 if (src.Trim () == "" || src.IndexOfAny (Path.InvalidPathChars) != -1)
359 throw new ArgumentException ("Invalid source directory name: " + src, "src");
361 if (dest.Trim () == "" || dest.IndexOfAny (Path.InvalidPathChars) != -1)
362 throw new ArgumentException ("Invalid target directory name: " + dest, "dest");
365 throw new IOException ("Source directory cannot be same as a target directory.");
368 throw new IOException (dest + " already exists.");
371 throw new DirectoryNotFoundException (src + " does not exist");
374 if (!MonoIO.MoveFile (src, dest, out error))
375 throw MonoIO.GetException (error);
378 public static void SetCreationTime (string path, DateTime creation_time)
380 File.SetCreationTime (path, creation_time);
383 public static void SetCreationTimeUtc (string path, DateTime creation_time)
385 SetCreationTime (path, creation_time.ToLocalTime ());
388 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
389 public static void SetCurrentDirectory (string path)
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");
399 throw new DirectoryNotFoundException ("Directory \"" +
400 path + "\" not found.");
402 MonoIO.SetCurrentDirectory (path, out error);
403 if (error != MonoIOError.ERROR_SUCCESS)
404 throw MonoIO.GetException (path, error);
407 public static void SetLastAccessTime (string path, DateTime last_access_time)
409 File.SetLastAccessTime (path, last_access_time);
412 public static void SetLastAccessTimeUtc (string path, DateTime last_access_time)
414 SetLastAccessTime (path, last_access_time.ToLocalTime ());
417 public static void SetLastWriteTime (string path, DateTime last_write_time)
419 File.SetLastWriteTime (path, last_write_time);
422 public static void SetLastWriteTimeUtc (string path, DateTime last_write_time)
424 SetLastWriteTime (path, last_write_time.ToLocalTime ());
429 private static void CheckPathExceptions (string path)
432 throw new System.ArgumentNullException("Path is Null");
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");
441 private static string [] GetFileSystemEntries (string path, string pattern, FileAttributes mask, FileAttributes attrs)
443 if (path == null || pattern == null)
444 throw new ArgumentNullException ();
446 if (pattern == String.Empty)
447 return new string [] {};
449 if (path.Trim () == "")
450 throw new ArgumentException ("The Path does not have a valid format");
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");
457 if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1) {
458 if (path.IndexOfAny (SearchPattern.InvalidChars) == -1)
459 throw new ArgumentException ("Path contains invalid characters", "path");
461 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 return new string [] { wildpath };
473 if (error != MonoIOError.ERROR_PATH_NOT_FOUND)
474 throw MonoIO.GetException (wildpath, error);
476 if (wildpath.IndexOfAny (SearchPattern.WildcardChars) == -1)
477 throw new DirectoryNotFoundException ("Directory '" + wildpath + "' not found.");
479 if (path.IndexOfAny (SearchPattern.WildcardChars) == -1)
480 throw new ArgumentException ("Pattern is invalid", "pattern");
482 throw new ArgumentException ("Path is invalid", "path");
485 string [] result = MonoIO.GetFileSystemEntries (wildpath, pattern, (int) attrs, (int) mask, out error);
487 throw MonoIO.GetException (wildpath, error);