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 throw MonoIO.GetException (path, error);
111 public static void Delete (string path)
114 throw new ArgumentNullException ("path");
117 throw new ArgumentException ("Path is empty");
119 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
120 throw new ArgumentException ("Path contains invalid chars");
122 if (path.Trim().Length == 0)
123 throw new ArgumentException ("Only blank characters in path");
126 throw new NotSupportedException ("Only ':' In path");
130 if (!MonoIO.RemoveDirectory (path, out error)) {
133 * In io-layer/io.c rmdir returns error_file_not_found if directory does not exists.
134 * So maybe this could be handled somewhere else?
136 if (error == MonoIOError.ERROR_FILE_NOT_FOUND)
137 throw new DirectoryNotFoundException ("Directory '" + path + "' doesnt exists.");
139 throw MonoIO.GetException (path, error);
143 static void RecursiveDelete (string path)
145 foreach (string dir in GetDirectories (path))
146 RecursiveDelete (dir);
148 foreach (string file in GetFiles (path))
151 Directory.Delete (path);
154 public static void Delete (string path, bool recurse)
156 CheckPathExceptions (path);
158 if (recurse == false){
163 RecursiveDelete (path);
166 public static bool Exists (string path)
174 exists = MonoIO.ExistsDirectory (path, out error);
175 if (error != MonoIOError.ERROR_SUCCESS &&
176 error != MonoIOError.ERROR_PATH_NOT_FOUND) {
177 throw MonoIO.GetException (path, error);
183 public static DateTime GetLastAccessTime (string path)
185 return File.GetLastAccessTime (path);
188 public static DateTime GetLastAccessTimeUtc (string path)
190 return GetLastAccessTime (path).ToUniversalTime ();
193 public static DateTime GetLastWriteTime (string path)
195 return File.GetLastWriteTime (path);
198 public static DateTime GetLastWriteTimeUtc (string path)
200 return GetLastWriteTime (path).ToUniversalTime ();
203 public static DateTime GetCreationTime (string path)
205 return File.GetCreationTime (path);
208 public static DateTime GetCreationTimeUtc (string path)
210 return GetCreationTime (path).ToUniversalTime ();
213 public static string GetCurrentDirectory ()
217 string result = MonoIO.GetCurrentDirectory (out error);
218 if (error != MonoIOError.ERROR_SUCCESS)
219 throw MonoIO.GetException (error);
221 if ((result != null) && (result.Length > 0) && SecurityManager.SecurityEnabled) {
222 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, result).Demand ();
227 public static string [] GetDirectories (string path)
229 return GetDirectories (path, "*");
232 public static string [] GetDirectories (string path, string pattern)
234 return GetFileSystemEntries (path, pattern, FileAttributes.Directory, FileAttributes.Directory);
237 public static string GetDirectoryRoot (string path)
239 return new String(Path.DirectorySeparatorChar,1);
242 public static string [] GetFiles (string path)
244 return GetFiles (path, "*");
247 public static string [] GetFiles (string path, string pattern)
249 return GetFileSystemEntries (path, pattern, FileAttributes.Directory, 0);
252 public static string [] GetFileSystemEntries (string path)
254 return GetFileSystemEntries (path, "*");
257 public static string [] GetFileSystemEntries (string path, string pattern)
259 return GetFileSystemEntries (path, pattern, 0, 0);
262 public static string[] GetLogicalDrives ()
264 return Environment.GetLogicalDrives ();
267 static bool IsRootDirectory (string path)
270 if (Path.DirectorySeparatorChar == '/' && path == "/")
274 if (Path.DirectorySeparatorChar == '\\')
275 if (path.Length == 3 && path.EndsWith (":\\"))
281 public static DirectoryInfo GetParent (string path)
284 throw new ArgumentNullException ();
285 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
286 throw new ArgumentException ("Path contains invalid characters");
288 throw new ArgumentException ("The Path do not have a valid format");
290 // return null if the path is the root directory
291 if (IsRootDirectory (path))
294 return new DirectoryInfo (Path.GetDirectoryName (path));
297 public static void Move (string src, string dest)
300 throw new ArgumentNullException ("src");
303 throw new ArgumentNullException ("dest");
305 if (src.Trim () == "" || src.IndexOfAny (Path.InvalidPathChars) != -1)
306 throw new ArgumentException ("Invalid source directory name: " + src, "src");
308 if (dest.Trim () == "" || dest.IndexOfAny (Path.InvalidPathChars) != -1)
309 throw new ArgumentException ("Invalid target directory name: " + dest, "dest");
312 throw new IOException ("Source directory cannot be same as a target directory.");
315 throw new IOException (dest + " already exists.");
318 throw new DirectoryNotFoundException (src + " does not exist");
321 if (!MonoIO.MoveFile (src, dest, out error))
322 throw MonoIO.GetException (error);
325 public static void SetCreationTime (string path, DateTime creation_time)
327 File.SetCreationTime (path, creation_time);
330 public static void SetCreationTimeUtc (string path, DateTime creation_time)
332 SetCreationTime (path, creation_time.ToLocalTime ());
335 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
336 public static void SetCurrentDirectory (string path)
339 throw new ArgumentNullException ("path");
340 if (path.Trim () == String.Empty)
341 throw new ArgumentException ("path string must not be an empty string or whitespace string");
346 throw new DirectoryNotFoundException ("Directory \"" +
347 path + "\" not found.");
349 MonoIO.SetCurrentDirectory (path, out error);
350 if (error != MonoIOError.ERROR_SUCCESS)
351 throw MonoIO.GetException (path, error);
354 public static void SetLastAccessTime (string path, DateTime last_access_time)
356 File.SetLastAccessTime (path, last_access_time);
359 public static void SetLastAccessTimeUtc (string path, DateTime last_access_time)
361 SetLastAccessTime (path, last_access_time.ToLocalTime ());
364 public static void SetLastWriteTime (string path, DateTime last_write_time)
366 File.SetLastWriteTime (path, last_write_time);
369 public static void SetLastWriteTimeUtc (string path, DateTime last_write_time)
371 SetLastWriteTime (path, last_write_time.ToLocalTime ());
376 private static void CheckPathExceptions (string path)
379 throw new System.ArgumentNullException("Path is Null");
381 throw new System.ArgumentException("Path is Empty");
382 if (path.Trim().Length == 0)
383 throw new ArgumentException ("Only blank characters in path");
384 if (path.IndexOfAny (Path.InvalidPathChars) != -1)
385 throw new ArgumentException ("Path contains invalid chars");
388 private static string [] GetFileSystemEntries (string path, string pattern, FileAttributes mask, FileAttributes attrs)
393 if (path == null || pattern == null)
394 throw new ArgumentNullException ();
396 if (pattern == String.Empty)
397 return new string [] {};
399 if (path.Trim () == "")
400 throw new ArgumentException ("The Path does not have a valid format");
402 string wild = Path.Combine (path, pattern);
403 string wildpath = Path.GetDirectoryName (wild);
404 if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1)
405 throw new ArgumentException ("Path contains invalid characters");
407 if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1) {
408 if (path.IndexOfAny (SearchPattern.InvalidChars) == -1)
409 throw new ArgumentException ("Path contains invalid characters", "path");
411 throw new ArgumentException ("Pattern contains invalid characters", "pattern");
415 if (!MonoIO.ExistsDirectory (wildpath, out error)) {
416 if (error != MonoIOError.ERROR_PATH_NOT_FOUND)
417 throw MonoIO.GetException (wildpath, error);
419 if (wildpath.IndexOfAny (SearchPattern.WildcardChars) == -1)
420 throw new DirectoryNotFoundException ("Directory '" + wildpath + "' not found.");
422 if (path.IndexOfAny (SearchPattern.WildcardChars) == -1)
423 throw new ArgumentException ("Pattern is invalid", "pattern");
425 throw new ArgumentException ("Path is invalid", "path");
428 find = MonoIO.FindFirstFile (wild, out stat, out error);
429 if (find == MonoIO.InvalidHandle) {
431 case MonoIOError.ERROR_PATH_NOT_FOUND:
432 string message = String.Format ("Could not find a part of the path \"{0}\"",
434 throw new DirectoryNotFoundException (message);
435 case MonoIOError.ERROR_FILE_NOT_FOUND:
436 case MonoIOError.ERROR_NO_MORE_FILES:
437 return new string [0];
440 throw MonoIO.GetException (wildpath, error);
444 ArrayList entries = new ArrayList ();
447 if ((stat.Attributes & mask) == attrs)
448 entries.Add (Path.Combine (wildpath, stat.Name));
449 } while (MonoIO.FindNextFile (find, out stat, out error));
451 MonoIO.FindClose (find, out error);
453 return (string []) entries.ToArray (typeof (string));