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