Merge pull request #475 from pruiz/xamarin-bug-7408
[mono.git] / mcs / class / corlib / System.IO / DirectoryInfo.cs
1 // 
2 // System.IO.DirectoryInfo.cs 
3 //
4 // Authors:
5 //   Miguel de Icaza, miguel@ximian.com
6 //   Jim Richardson, develop@wtfo-guru.com
7 //   Dan Lewis, dihlewis@yahoo.co.uk
8 //   Sebastien Pouliot  <sebastien@ximian.com>
9 //
10 // Copyright (C) 2002 Ximian, Inc.
11 // Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
12 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System.Collections;
35 using System.Collections.Generic;
36 using System.Runtime.InteropServices;
37 using System.Runtime.Serialization;
38 using System.Security;
39 using System.Text;
40 #if !MOONLIGHT
41 using System.Security.AccessControl;
42 #endif
43
44 namespace System.IO {
45         
46         [Serializable]
47         [ComVisible (true)]
48         public sealed class DirectoryInfo : FileSystemInfo {
49
50                 private string current;
51                 private string parent;
52         
53 #if MOONLIGHT
54                 internal DirectoryInfo ()
55                 {
56                 }
57 #endif
58                 public DirectoryInfo (string path) : this (path, false)
59                 {
60                 }
61
62                 internal DirectoryInfo (string path, bool simpleOriginalPath)
63                 {
64                         CheckPath (path);
65
66                         SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
67
68                         FullPath = Path.GetFullPath (path);
69                         if (simpleOriginalPath)
70                                 OriginalPath = Path.GetFileName (path);
71                         else
72                                 OriginalPath = path;
73
74                         Initialize ();
75                 }
76
77                 private DirectoryInfo (SerializationInfo info, StreamingContext context)
78                         : base (info, context)
79                 {
80                         Initialize ();
81                 }
82
83                 void Initialize ()
84                 {
85                         int len = FullPath.Length - 1;
86                         if ((len > 1) && (FullPath [len] == Path.DirectorySeparatorChar))
87                                 len--;
88                         int last = FullPath.LastIndexOf (Path.DirectorySeparatorChar, len);
89                         if ((last == -1) || ((last == 0) && (len == 0))) {
90                                 current = FullPath;
91                                 parent = null;
92                         } else {
93                                 current = FullPath.Substring (last + 1, len - last);
94                                 if (last == 0 && !Environment.IsRunningOnWindows)
95                                         parent = Path.DirectorySeparatorStr;
96                                 else
97                                         parent = FullPath.Substring (0, last);
98                                 // adjust for drives, i.e. a special case for windows
99                                 if (Environment.IsRunningOnWindows) {
100                                         if ((parent.Length == 2) && (parent [1] == ':') && Char.IsLetter (parent [0]))
101                                                 parent += Path.DirectorySeparatorChar;
102                                 }
103                         }
104                 }
105
106                 // properties
107
108                 public override bool Exists {
109                         get {
110                                 Refresh (false);
111
112                                 if (stat.Attributes == MonoIO.InvalidFileAttributes)
113                                         return false;
114
115                                 if ((stat.Attributes & FileAttributes.Directory) == 0)
116                                         return false;
117
118                                 return true;
119                         }
120                 }
121
122                 public override string Name {
123                         get { return current; }
124                 }
125
126                 public DirectoryInfo Parent {
127                         get {
128                                 if ((parent == null) || (parent.Length == 0))
129                                         return null;
130                                 return new DirectoryInfo (parent);
131                         }
132                 }
133
134                 public DirectoryInfo Root {
135                         get {
136                                 string root = Path.GetPathRoot (FullPath);
137                                 if (root == null)
138                                         return null;
139
140                                 return new DirectoryInfo (root);
141                         }
142                 }
143
144                 // creational methods
145
146                 public void Create ()
147                 {
148                         Directory.CreateDirectory (FullPath);
149                 }
150
151                 public DirectoryInfo CreateSubdirectory (string path)
152                 {
153                         CheckPath (path);
154
155                         path = Path.Combine (FullPath, path);
156                         Directory.CreateDirectory (path);
157                         return new DirectoryInfo (path);
158                 }
159
160                 // directory listing methods
161
162                 public FileInfo [] GetFiles ()
163                 {
164                         return GetFiles ("*");
165                 }
166
167                 public FileInfo [] GetFiles (string searchPattern)
168                 {
169                         if (searchPattern == null)
170                                 throw new ArgumentNullException ("searchPattern");
171
172                         string [] names = Directory.GetFiles (FullPath, searchPattern);
173
174                         FileInfo[] infos = new FileInfo [names.Length];
175                         int i = 0;
176                         foreach (string name in names)
177                                 infos [i++] = new FileInfo (name);
178
179                         return infos;
180                 }
181
182                 public DirectoryInfo [] GetDirectories ()
183                 {
184                         return GetDirectories ("*");
185                 }
186
187                 public DirectoryInfo [] GetDirectories (string searchPattern)
188                 {
189                         if (searchPattern == null)
190                                 throw new ArgumentNullException ("searchPattern");
191
192                         string [] names = Directory.GetDirectories (FullPath, searchPattern);
193
194                         DirectoryInfo[] infos = new DirectoryInfo [names.Length];
195                         int i = 0;
196                         foreach (string name in names)
197                                 infos [i++] = new DirectoryInfo (name);
198
199                         return infos;
200                 }
201
202                 public FileSystemInfo [] GetFileSystemInfos ()
203                 {
204                         return GetFileSystemInfos ("*");
205                 }
206
207                 public FileSystemInfo [] GetFileSystemInfos (string searchPattern)
208                 {
209                         return GetFileSystemInfos (searchPattern, SearchOption.TopDirectoryOnly);
210                 }
211
212 #if NET_4_0
213                 public
214 #endif
215                 FileSystemInfo [] GetFileSystemInfos (string searchPattern, SearchOption searchOption)
216                 {
217                         if (searchPattern == null)
218                                 throw new ArgumentNullException ("searchPattern");
219                         if (searchOption != SearchOption.TopDirectoryOnly && searchOption != SearchOption.AllDirectories)
220                                 throw new ArgumentOutOfRangeException ("searchOption", "Must be TopDirectoryOnly or AllDirectories");
221                         if (!Directory.Exists (FullPath))
222                                 throw new IOException ("Invalid directory");
223
224                         List<FileSystemInfo> infos = new List<FileSystemInfo> ();
225                         InternalGetFileSystemInfos (searchPattern, searchOption, infos);
226                         return infos.ToArray ();
227                 }
228
229                 void InternalGetFileSystemInfos (string searchPattern, SearchOption searchOption, List<FileSystemInfo> infos)
230                 {
231                         // UnauthorizedAccessExceptions might happen here and break everything for SearchOption.AllDirectories
232                         string [] dirs = Directory.GetDirectories (FullPath, searchPattern);
233                         string [] files = Directory.GetFiles (FullPath, searchPattern);
234
235                         Array.ForEach<string> (dirs, (dir) => { infos.Add (new DirectoryInfo (dir)); });
236                         Array.ForEach<string> (files, (file) => { infos.Add (new FileInfo (file)); });
237                         if (dirs.Length == 0 || searchOption == SearchOption.TopDirectoryOnly)
238                                 return;
239
240                         foreach (string dir in dirs) {
241                                 DirectoryInfo dinfo = new DirectoryInfo (dir);
242                                 dinfo.InternalGetFileSystemInfos (searchPattern, searchOption, infos);
243                         }
244                 }
245
246                 // directory management methods
247
248                 public override void Delete ()
249                 {
250                         Delete (false);
251                 }
252
253                 public void Delete (bool recursive)
254                 {
255                         Directory.Delete (FullPath, recursive);
256                 }
257
258                 public void MoveTo (string destDirName)
259                 {
260                         if (destDirName == null)
261                                 throw new ArgumentNullException ("destDirName");
262                         if (destDirName.Length == 0)
263                                 throw new ArgumentException ("An empty file name is not valid.", "destDirName");
264
265                         Directory.Move (FullPath, Path.GetFullPath (destDirName));
266                         FullPath = OriginalPath = destDirName;
267                         Initialize ();
268                 }
269
270                 public override string ToString ()
271                 {
272                         return OriginalPath;
273                 }
274
275 #if !MOONLIGHT
276                 public DirectoryInfo[] GetDirectories (string searchPattern, SearchOption searchOption)
277                 {
278                     //NULL-check of searchPattern is done in Directory.GetDirectories
279                         string [] names = Directory.GetDirectories (FullPath, searchPattern, searchOption);
280                         //Convert the names to DirectoryInfo instances
281                         DirectoryInfo[] infos = new DirectoryInfo [names.Length];
282                         for (int i = 0; i<names.Length; ++i){
283                                 string name = names[i];
284                                 infos [i] = new DirectoryInfo (name);
285                         }
286                         return infos;
287                 }       
288
289                 internal int GetFilesSubdirs (ArrayList l, string pattern)
290                 {
291                         int count;
292                         FileInfo [] thisdir = null;
293
294                         try {
295                                 thisdir = GetFiles (pattern);
296                         } catch (System.UnauthorizedAccessException){
297                                 return 0;
298                         }
299                         
300                         count = thisdir.Length;
301                         l.Add (thisdir);
302
303                         foreach (DirectoryInfo subdir in GetDirectories ()){
304                                 count += subdir.GetFilesSubdirs (l, pattern);
305                         }
306                         return count;
307                 }
308                 
309                 public FileInfo[] GetFiles (string searchPattern, SearchOption searchOption)
310                 {
311                         switch (searchOption) {
312                         case SearchOption.TopDirectoryOnly:
313                                 return GetFiles (searchPattern);
314                         case SearchOption.AllDirectories: {
315                                 ArrayList groups = new ArrayList ();
316                                 int count = GetFilesSubdirs (groups, searchPattern);
317                                 int current = 0;
318                                 
319                                 FileInfo [] all = new FileInfo [count];
320                                 foreach (FileInfo [] p in groups){
321                                         p.CopyTo (all, current);
322                                         current += p.Length;
323                                 }
324                                 return all;
325                         }
326                         default:
327                                 string msg = Locale.GetText ("Invalid enum value '{0}' for '{1}'.", searchOption, "SearchOption");
328                                 throw new ArgumentOutOfRangeException ("searchOption", msg);
329                         }
330                 }
331
332                 // access control methods
333
334                 [MonoLimitation ("DirectorySecurity isn't implemented")]
335                 public void Create (DirectorySecurity directorySecurity)
336                 {
337                         if (directorySecurity != null)
338                                 throw new UnauthorizedAccessException ();
339                         Create ();
340                 }
341
342                 [MonoLimitation ("DirectorySecurity isn't implemented")]
343                 public DirectoryInfo CreateSubdirectory (string path, DirectorySecurity directorySecurity)
344                 {
345                         if (directorySecurity != null)
346                                 throw new UnauthorizedAccessException ();
347                         return CreateSubdirectory (path);
348                 }
349
350                 public DirectorySecurity GetAccessControl ()
351                 {
352                         return Directory.GetAccessControl (FullPath);
353                 }
354
355                 public DirectorySecurity GetAccessControl (AccessControlSections includeSections)
356                 {
357                         return Directory.GetAccessControl (FullPath, includeSections);
358                 }
359
360                 public void SetAccessControl (DirectorySecurity directorySecurity)
361                 {
362                         Directory.SetAccessControl (FullPath, directorySecurity);
363                 }
364 #endif
365
366 #if NET_4_0 || MOONLIGHT || MOBILE
367
368                 public IEnumerable<DirectoryInfo> EnumerateDirectories ()
369                 {
370                         return EnumerateDirectories ("*", SearchOption.TopDirectoryOnly);
371                 }
372
373                 public IEnumerable<DirectoryInfo> EnumerateDirectories (string searchPattern)
374                 {
375                         return EnumerateDirectories (searchPattern, SearchOption.TopDirectoryOnly);
376                 }
377
378                 public IEnumerable<DirectoryInfo> EnumerateDirectories (string searchPattern, SearchOption searchOption)
379                 {
380                         if (searchPattern == null)
381                                 throw new ArgumentNullException ("searchPattern");
382
383                         return CreateEnumerateDirectoriesIterator (searchPattern, searchOption);
384                 }
385
386                 IEnumerable<DirectoryInfo> CreateEnumerateDirectoriesIterator (string searchPattern, SearchOption searchOption)
387                 {
388                         foreach (string name in Directory.EnumerateDirectories (FullPath, searchPattern, searchOption))
389                                 yield return new DirectoryInfo (name);
390                 }
391
392                 public IEnumerable<FileInfo> EnumerateFiles ()
393                 {
394                         return EnumerateFiles ("*", SearchOption.TopDirectoryOnly);
395                 }
396
397                 public IEnumerable<FileInfo> EnumerateFiles (string searchPattern)
398                 {
399                         return EnumerateFiles (searchPattern, SearchOption.TopDirectoryOnly);
400                 }
401
402                 public IEnumerable<FileInfo> EnumerateFiles (string searchPattern, SearchOption searchOption)
403                 {
404                         if (searchPattern == null)
405                                 throw new ArgumentNullException ("searchPattern");
406
407                         return CreateEnumerateFilesIterator (searchPattern, searchOption);
408                 }
409
410                 IEnumerable<FileInfo> CreateEnumerateFilesIterator (string searchPattern, SearchOption searchOption)
411                 {
412                         foreach (string name in Directory.EnumerateFiles (FullPath, searchPattern, searchOption))
413                                 yield return new FileInfo (name);
414                 }
415
416                 public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos ()
417                 {
418                         return EnumerateFileSystemInfos ("*", SearchOption.TopDirectoryOnly);
419                 }
420
421                 public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos (string searchPattern)
422                 {
423                         return EnumerateFileSystemInfos (searchPattern, SearchOption.TopDirectoryOnly);
424                 }
425
426                 public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos (string searchPattern, SearchOption searchOption)
427                 {
428                         if (searchPattern == null)
429                                 throw new ArgumentNullException ("searchPattern");
430                         if (searchOption != SearchOption.TopDirectoryOnly && searchOption != SearchOption.AllDirectories)
431                                 throw new ArgumentOutOfRangeException ("searchoption");
432
433                         return EnumerateFileSystemInfos (FullPath, searchPattern, searchOption);
434                 }
435
436                 static internal IEnumerable<FileSystemInfo> EnumerateFileSystemInfos (string full, string searchPattern, SearchOption searchOption)
437                 {
438                         string path_with_pattern = Path.Combine (full, searchPattern);
439                         IntPtr handle;
440                         MonoIOError error;
441                         FileAttributes rattr;
442                         bool subdirs = searchOption == SearchOption.AllDirectories;
443
444                         Path.Validate (full);
445                         
446                         string s = MonoIO.FindFirst (full, path_with_pattern, out rattr, out error, out handle);
447                         if (s == null)
448                                 yield break;
449                         if (error != 0)
450                                 throw MonoIO.GetException (Path.GetDirectoryName (path_with_pattern), (MonoIOError) error);
451
452                         try {
453                                 if (((rattr & FileAttributes.ReparsePoint) == 0)){
454                                         if ((rattr & FileAttributes.Directory) != 0)
455                                                 yield return new DirectoryInfo (s);
456                                         else
457                                                 yield return new FileInfo (s);
458                                 }
459                                 
460                                 while ((s = MonoIO.FindNext (handle, out rattr, out error)) != null){
461                                         if ((rattr & FileAttributes.ReparsePoint) != 0)
462                                                 continue;
463                                         if ((rattr & FileAttributes.Directory) != 0)
464                                                 yield return new DirectoryInfo (s);
465                                         else
466                                                 yield return new FileInfo (s);
467                                         
468                                         if (((rattr & FileAttributes.Directory) != 0) && subdirs)
469                                                 foreach (FileSystemInfo child in EnumerateFileSystemInfos (s, searchPattern, searchOption))
470                                                         yield return child;
471                                 }
472                         } finally {
473                                 MonoIO.FindClose (handle);
474                         }
475                 }
476                 
477                 
478 #endif
479         }
480 }