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");
75 // LAMESPEC: with .net 1.0 version this throw NotSupportedException and msdn says so too
76 // but v1.1 throws ArgumentException.
78 throw new ArgumentException ("Only ':' In path");
80 return CreateDirectoriesInternal (path);
83 static DirectoryInfo CreateDirectoriesInternal (string path)
85 if (SecurityManager.SecurityEnabled) {
86 new FileIOPermission (FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, path).Demand ();
89 DirectoryInfo info = new DirectoryInfo (path);
90 if (info.Parent != null && !info.Parent.Exists)
91 info.Parent.Create ();
94 if (!MonoIO.CreateDirectory (path, out error)) {
95 // LAMESPEC: 1.1 and 1.2alpha allow CreateDirectory on a file path.
96 // So CreateDirectory ("/tmp/somefile") will succeed if 'somefile' is
97 // not a directory. However, 1.0 will throw an exception.
98 // We behave like 1.0 here (emulating 1.1-like behavior is just a matter
99 // of comparing error to ERROR_FILE_EXISTS, but it's lame to do:
100 // DirectoryInfo di = Directory.CreateDirectory (something);
101 // and having di.Exists return false afterwards.
102 // I hope we don't break anyone's code, as they should be catching
103 // the exception anyway.
104 if (error != MonoIOError.ERROR_ALREADY_EXISTS &&
105 error != MonoIOError.ERROR_FILE_EXISTS)
106 throw MonoIO.GetException (path, error);
112 public static void Delete (string path)
115 throw new ArgumentNullException ("path");
118 throw new ArgumentException ("Path is empty");
120 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
121 throw new ArgumentException ("Path contains invalid chars");
123 if (path.Trim().Length == 0)
124 throw new ArgumentException ("Only blank characters in path");
127 throw new NotSupportedException ("Only ':' In path");
131 if (!MonoIO.RemoveDirectory (path, out error)) {
134 * In io-layer/io.c rmdir returns error_file_not_found if directory does not exists.
135 * So maybe this could be handled somewhere else?
137 if (error == MonoIOError.ERROR_FILE_NOT_FOUND)
138 throw new DirectoryNotFoundException ("Directory '" + path + "' doesnt exists.");
140 throw MonoIO.GetException (path, error);
144 static void RecursiveDelete (string path)
146 foreach (string dir in GetDirectories (path))
147 RecursiveDelete (dir);
149 foreach (string file in GetFiles (path))
152 Directory.Delete (path);
155 public static void Delete (string path, bool recurse)
157 CheckPathExceptions (path);
159 if (recurse == false){
164 RecursiveDelete (path);
167 public static bool Exists (string path)
175 exists = MonoIO.ExistsDirectory (path, out error);
176 if (error != MonoIOError.ERROR_SUCCESS &&
177 error != MonoIOError.ERROR_PATH_NOT_FOUND &&
178 error != MonoIOError.ERROR_INVALID_HANDLE &&
179 error != MonoIOError.ERROR_ACCESS_DENIED) {
181 // INVALID_HANDLE might happen if the file is moved
182 // while testing for the existence, a kernel issue
183 // according to Larry Ewing.
185 throw MonoIO.GetException (path, error);
191 public static DateTime GetLastAccessTime (string path)
193 return File.GetLastAccessTime (path);
196 public static DateTime GetLastAccessTimeUtc (string path)
198 return GetLastAccessTime (path).ToUniversalTime ();
201 public static DateTime GetLastWriteTime (string path)
203 return File.GetLastWriteTime (path);
206 public static DateTime GetLastWriteTimeUtc (string path)
208 return GetLastWriteTime (path).ToUniversalTime ();
211 public static DateTime GetCreationTime (string path)
213 return File.GetCreationTime (path);
216 public static DateTime GetCreationTimeUtc (string path)
218 return GetCreationTime (path).ToUniversalTime ();
221 public static string GetCurrentDirectory ()
225 string result = MonoIO.GetCurrentDirectory (out error);
226 if (error != MonoIOError.ERROR_SUCCESS)
227 throw MonoIO.GetException (error);
229 if ((result != null) && (result.Length > 0) && SecurityManager.SecurityEnabled) {
230 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, result).Demand ();
235 public static string [] GetDirectories (string path)
237 return GetDirectories (path, "*");
240 public static string [] GetDirectories (string path, string pattern)
242 return GetFileSystemEntries (path, pattern, FileAttributes.Directory, FileAttributes.Directory);
246 public static string [] GetDirectories (string path, string pattern, SearchOption option)
248 if (option == SearchOption.TopDirectoryOnly)
249 return GetDirectories (path, pattern);
250 ArrayList all = new ArrayList ();
251 GetDirectoriesRecurse (path, pattern, all);
252 return (string []) all.ToArray (typeof (string));
255 static void GetDirectoriesRecurse (string path, string pattern, ArrayList all)
257 all.AddRange (GetDirectories (path, pattern));
258 foreach (string dir in GetDirectories (path))
259 GetDirectoriesRecurse (dir, pattern, all);
263 public static string GetDirectoryRoot (string path)
265 return new String(Path.DirectorySeparatorChar,1);
268 public static string [] GetFiles (string path)
270 return GetFiles (path, "*");
273 public static string [] GetFiles (string path, string pattern)
275 return GetFileSystemEntries (path, pattern, FileAttributes.Directory, 0);
279 public static string[] GetFiles (string path, string searchPattern, SearchOption searchOption)
281 if (searchOption == SearchOption.TopDirectoryOnly)
282 return GetFiles (path, searchPattern);
283 ArrayList all = new ArrayList ();
284 GetFilesRecurse (path, searchPattern, all);
285 return (string []) all.ToArray (typeof (string));
288 static void GetFilesRecurse (string path, string pattern, ArrayList all)
290 all.AddRange (GetFiles (path, pattern));
291 foreach (string dir in GetDirectories (path))
292 GetFilesRecurse (dir, pattern, all);
296 public static string [] GetFileSystemEntries (string path)
298 return GetFileSystemEntries (path, "*");
301 public static string [] GetFileSystemEntries (string path, string pattern)
303 return GetFileSystemEntries (path, pattern, 0, 0);
306 public static string[] GetLogicalDrives ()
308 return Environment.GetLogicalDrives ();
311 static bool IsRootDirectory (string path)
314 if (Path.DirectorySeparatorChar == '/' && path == "/")
318 if (Path.DirectorySeparatorChar == '\\')
319 if (path.Length == 3 && path.EndsWith (":\\"))
325 public static DirectoryInfo GetParent (string path)
328 throw new ArgumentNullException ();
329 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
330 throw new ArgumentException ("Path contains invalid characters");
332 throw new ArgumentException ("The Path do not have a valid format");
334 // return null if the path is the root directory
335 if (IsRootDirectory (path))
338 string parent_name = Path.GetDirectoryName (path);
339 if (parent_name == "")
340 parent_name = GetCurrentDirectory();
342 return new DirectoryInfo (parent_name);
345 public static void Move (string src, string dest)
348 throw new ArgumentNullException ("src");
351 throw new ArgumentNullException ("dest");
353 if (src.Trim () == "" || src.IndexOfAny (Path.InvalidPathChars) != -1)
354 throw new ArgumentException ("Invalid source directory name: " + src, "src");
356 if (dest.Trim () == "" || dest.IndexOfAny (Path.InvalidPathChars) != -1)
357 throw new ArgumentException ("Invalid target directory name: " + dest, "dest");
360 throw new IOException ("Source directory cannot be same as a target directory.");
363 throw new IOException (dest + " already exists.");
366 throw new DirectoryNotFoundException (src + " does not exist");
369 if (!MonoIO.MoveFile (src, dest, out error))
370 throw MonoIO.GetException (error);
373 public static void SetCreationTime (string path, DateTime creation_time)
375 File.SetCreationTime (path, creation_time);
378 public static void SetCreationTimeUtc (string path, DateTime creation_time)
380 SetCreationTime (path, creation_time.ToLocalTime ());
383 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
384 public static void SetCurrentDirectory (string path)
387 throw new ArgumentNullException ("path");
388 if (path.Trim () == String.Empty)
389 throw new ArgumentException ("path string must not be an empty string or whitespace string");
394 throw new DirectoryNotFoundException ("Directory \"" +
395 path + "\" not found.");
397 MonoIO.SetCurrentDirectory (path, out error);
398 if (error != MonoIOError.ERROR_SUCCESS)
399 throw MonoIO.GetException (path, error);
402 public static void SetLastAccessTime (string path, DateTime last_access_time)
404 File.SetLastAccessTime (path, last_access_time);
407 public static void SetLastAccessTimeUtc (string path, DateTime last_access_time)
409 SetLastAccessTime (path, last_access_time.ToLocalTime ());
412 public static void SetLastWriteTime (string path, DateTime last_write_time)
414 File.SetLastWriteTime (path, last_write_time);
417 public static void SetLastWriteTimeUtc (string path, DateTime last_write_time)
419 SetLastWriteTime (path, last_write_time.ToLocalTime ());
424 private static void CheckPathExceptions (string path)
427 throw new System.ArgumentNullException("Path is Null");
429 throw new System.ArgumentException("Path is Empty");
430 if (path.Trim().Length == 0)
431 throw new ArgumentException ("Only blank characters in path");
432 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
433 throw new ArgumentException ("Path contains invalid chars");
436 private static string [] GetFileSystemEntries (string path, string pattern, FileAttributes mask, FileAttributes attrs)
438 if (path == null || pattern == null)
439 throw new ArgumentNullException ();
441 if (pattern == String.Empty)
442 return new string [] {};
444 if (path.Trim () == "")
445 throw new ArgumentException ("The Path does not have a valid format");
447 string wild = Path.Combine (path, pattern);
448 string wildpath = Path.GetDirectoryName (wild);
449 if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1)
450 throw new ArgumentException ("Path contains invalid characters");
452 if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1) {
453 if (path.IndexOfAny (SearchPattern.InvalidChars) == -1)
454 throw new ArgumentException ("Path contains invalid characters", "path");
456 throw new ArgumentException ("Pattern contains invalid characters", "pattern");
460 if (!MonoIO.ExistsDirectory (wildpath, out error)) {
461 if (error == MonoIOError.ERROR_SUCCESS) {
462 MonoIOError file_error;
463 if (MonoIO.ExistsFile (wildpath, out file_error)) {
464 return new string [] { wildpath };
468 if (error != MonoIOError.ERROR_PATH_NOT_FOUND)
469 throw MonoIO.GetException (wildpath, error);
471 if (wildpath.IndexOfAny (SearchPattern.WildcardChars) == -1)
472 throw new DirectoryNotFoundException ("Directory '" + wildpath + "' not found.");
474 if (path.IndexOfAny (SearchPattern.WildcardChars) == -1)
475 throw new ArgumentException ("Pattern is invalid", "pattern");
477 throw new ArgumentException ("Path is invalid", "path");
480 string [] result = MonoIO.GetFileSystemEntries (wildpath, pattern, (int) attrs, (int) mask, out error);
482 throw MonoIO.GetException (wildpath, error);